C++ map max_size()
C++ map max_size()函数
C++地图 max_size()函数用于获取地图容器可以容纳的最大大小。
语法
成员类型 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
在上面的示例中,程序首先以给定的大小交互式地创建城市地图。然后,它会显示城市地图可以包含的总大小,每张地图的总大小以及地图中所有可用的名称和年龄。