C++映射 max_size()函数用于获取映射集合可以容纳的最大大小。
成员类型 size_type 是无符号整数类型。
size_type max_size() const;//until C++ 11 size_type max_size() const noexcept; //since C++ 11
没有
它返回映射集合的最大允许长度。
让我们看一个简单的示例来计算映射的最大尺寸。
#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()函数返回映射的最大尺寸。
让我们看一个简单的例子。
#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个元素。
让我们看一个简单的示例,查找一个空映射和一个非空映射的最大大小。
#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是一个空映射。但是,两个映射的最大大小是相同的。
让我们看一个简单的例子。
#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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)