C++ map max_size() 函数

C++ map max_size() 函数

C++ map 的 max_size() 函数用于获取一个 map 容器可以容纳的最大大小。

语法

成员类型 size_type 是一个无符号整数类型。

size_type max_size() const; // until C++ 11
size_type max_size() const noexcept; //since C++ 11

参数

返回值

它返回地图容器允许的最大长度。

示例1

让我们看一个简单的示例来计算地图的最大大小。

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<char,char> s;
    cout << "Maximum size of a 'map' is " << s.max_size() << "\n";
}

输出:

Maximum size of a 'map' is 461168601842738790

在上面的示例中,max_size()函数返回了映射的最大大小。

示例2

让我们看一个简单的示例。

#include <iostream>
#include <map>
 using namespace std;
 int main ()
{
  int i;
  map<int,int> mymap;

  if (mymap.max_size()>1000)
  {
    for (i=0; i<1000; i++) mymap[i]=0;
    cout << "The map contains 1000 elements.\n";
  }
  else cout << "The map could not hold 1000 elements.\n";

  return 0;
}

输出:

The map contains 1000 elements.

在上面的示例中,成员变量max_size用于事先检查地图是否允许插入1000个元素。

示例3

让我们看一个简单的示例,找出一个空地图和一个非空地图的最大大小。

#include <map>
#include <iostream>

using namespace std;

int main()
{

    // initialize container
    map<int, int> mp1, mp2;
    mp1[1] = 1111;

    // max size of Non-empty map
    cout << "The max size of mp1 is " << mp1.max_size();

    // max size of Empty-map
    cout << "\nThe max size of mp2 is " << mp2.max_size();
    return 0;
}

输出:

The max size of mp1 is 461168601842738790
The max size of mp2 is 461168601842738790

在上面的示例中,有两个地图,即m1和m2。m1是一个非空地图,m2是一个空地图。但是两个地图的最大大小是相同的。

示例4

让我们看一个简单的示例。

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {

  typedef map<string, int> city;  
   string name;
   int age;
   city fmly ;
   int n;

   cout<<"Enter the number of fmly members :";
   cin>>n;

   cout<<"Enter the name and age of each member: \n";
   for(int i =0; i<n; i++)
   {
       cin>> name;      // Get key
       cin>> age;    // Get value
       fmly[name] = age;   // Put them in map
   }

      cout<<"\nTotal number of population of city map: "<<fmly.max_size();
      cout<<"\nTotal memnber of fmly is:"<< fmly.size();

      cout<<"\nDetails of fmly members: \n";
      cout<<"\nName  |  Age \n ________________________\n";
      city::iterator p;
      for(p = fmly.begin(); p!=fmly.end(); p++)
      {
          cout<<(*p).first << " | " <<(*p).second <<" \n ";
      }

   return 0;
}

输出结果:

Enter the number of fmly members : 3
Enter the name and age of each member: 
Ram 42
Sita 37
Laxman 40

Total number of population of city map: 384307168202282325
Total memnber of fmly is:3
Details of fmly members: 

Name    |  Age 
__________________________
Laxman | 40 
Ram      | 42 
Sita       | 37

在上面的示例中,程序首先通过给定的大小数量,交互地创建城市地图。然后,它显示了城市地图可以容纳的总大小,家庭的总大小以及地图中所有可用的姓名和年龄。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程