C++ Set 中的 max_size函数

首页 / C++入门教程 / C++ Set 中的 max_size函数

C++ max_size()函数用于获取设置的集合可以容纳的最大大小数。

max_size - 语法

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

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

max_size - 返回值

它返回设置的集合的最大允许长度。

max_size - 例子1

让我们看一个简单的示例来计算集合的最大大小:

#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()函数返回集合的最大大小。

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个元素。

max_size - 例子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是一个空集。但是两组的最大大小是相同的。

max_size - 例子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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

微服务架构核心20讲 -〔杨波〕

大规模数据处理实战 -〔蔡元楠〕

全栈工程师修炼指南 -〔熊燚(四火)〕

DDD实战课 -〔欧创新〕

分布式协议与算法实战 -〔韩健〕

罗剑锋的C++实战笔记 -〔罗剑锋〕

正则表达式入门课 -〔涂伟忠〕

Web安全攻防实战 -〔王昊天〕

体验设计案例课 -〔炒炒〕

好记忆不如烂笔头。留下您的足迹吧 :)