C++ Set max_size()
 
 
 C++ Set max_size()
 
  C++ " max_size()函数用于获取 Set 的容器可以容纳的最大大小。
 
语法
 
 成员类型 size_type 是无符号整数类型。
 
 
  
  size_type max_size() const;               // until C++ 11
size_type max_size() const noexcept;    //since C++ 11
 
   
  
参数
 
 无
 
返回值
 
 它返回 Set 的容器的最大允许长度。 
 
复杂度
 
 常量。
 
迭代器有效性
 
 无变化。
 
数据竞争
 
 访问容器。
 
 同时访问集合的元素是安全的。
 
异常安全
 
 此成员函数从不抛出异常。
 
示例1 
 
 让我们看一个简单的示例来计算最大安全长度。 Set : 
 
 
  
  #include <iostream>
#include <set>
using namespace std;
 
int main()
{
    set<char,char> s;
    cout << "Maximum size of a 'set' is " << s.max_size() << "\n";
    return 0;
} 
   
  
  输出: 
 
 
  
   Maximum size of a 'set' is 461168601842738790
 
   
  
 在上面的示例中,max_size()函数返回集合的最大大小。 
 
示例2 
 
 让我们看一个简单的示例: 
 
 
  
  #include <iostream>
#include <set>
using namespace std;
int main ()
{
  int i;
  set<int> myset;
  if (myset.max_size()>1000)
  {
    for (i=0; i<1000; i++) myset.insert(0);
    cout << "The set contains 1000 elements.\n";
  }
  else cout << "The set could not hold 1000 elements.\n";
  return 0;
} 
   
  
  输出: 
 
 
  
  The set contains 1000 elements.
 
   
  
 在上面的示例中,成员max_size用于事先检查集合是否允许插入1000个元素。
 
示例3 
 
 查看一个简单的示例以查找一个空集和一个非空集的最大大小: 
 
 
  
  #include <set>
#include <iostream>
using namespace std;
 
int main()
{
 
    // initialize container
    set<int> mp1, mp2;
    mp1 = {1111};
 
    // max size of Non-empty set
    cout << "The max size of mp1 is " << mp1.max_size();
 
    // max size of Empty-set
    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 <set>
#include <string>
using namespace std;
int main() {
  typedef set<string> city;  
   string name;
   city fmly ;
   int n;
   cout<<"Enter the number of family members :";
   cin>>n;
   cout<<"Enter the name of each member: \n";
   for(int i =0; i<n; i++)
   {
       cin>> name;      // Get key
       fmly.insert(name);   // Put them in set
   }
   
      cout<<"\nTotal number of population of city set: "<<fmly.max_size();
      cout<<"\nTotal member of family is:"<< fmly.size();
      cout<<"\nName of family members: \n";
      cout<<"\nName \n ________________________\n";
      city::iterator p;
      for(p = fmly.begin(); p!=fmly.end(); p++)
      {
          cout<<(*p)<<" \n ";
      }
    
   return 0;
} 
   
  
  输出: 
 
 
  
  Enter the number of family members: 5
Enter the name of each member: 
Aman
Nikita
Divya
Amita
Kashish
Total number of population of city set: 461168601842738790
Total member of family is:5
Name of family members: 
Name 
 ________________________
Aman 
 Amita 
 Divya 
 Kashish 
 Nikita
 
   
  
 在上面的示例中,程序首先以给定的大小交互创建城市集。然后,它会显示城市集可以包含的总大小,每张照片的总大小以及该集合中可用的所有名称及其年龄。