C++ STL 中的 set::max_size() 函式


本文將討論 C++ STL 中的 set::max_size(),包括其語法、工作原理和返回值。

什麼是 C++ STL 中的 Set?

C++ STL 中的 Set 是一種容器,它必須包含按一般順序排列的唯一元素。Set 必須包含唯一元素,因為元素的值標識了該元素。一旦將值新增到 Set 容器中,以後就不能修改該值,儘管我們仍然可以從 Set 中刪除或新增值。Set 被用作二叉搜尋樹。

什麼是 set::max_size()?

max_size() 是 C++ STL 中的一個內建函式,它在 <set> 標頭檔案中宣告。max_size() 返回與其關聯的 Set 容器的最大大小。換句話說,它返回容器可以達到的最大大小,但是不能保證它可以分配該大小的元素,它仍然可能無法為 Set 容器的特定點分配儲存空間。

語法

name_of_set.max_size();

引數

此函式不接受任何引數。

返回值

此函式返回關聯的 Set 容器的最大大小。

示例

Input: set<int> myset;
myset.max_size();
Output: size of a set before inserting elements: 461168601842738790

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> data_1, data_2;
   data_1.insert(100);
   cout<<"size of a set after inserting values : "<<data_1.max_size()<< endl;
   cout<<"size of a set before inserting values : "<<data_2.max_size();
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

size of a set after inserting values : 461168601842738790
size of a set before inserting values : 461168601842738790

示例

 線上演示

#include <iostream>
#include <set>
int main (){
   int i;
   std::set<int> Set;
   if(Set.max_size()>1000){
      for (i=0; i<=1000; i++)
         Set.insert(i);
      std::cout<<"There are 1000 elements in a set.\n";
   }
   else
      std::cout<<"There can't be 1000 elements in a set.\n";
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

There are 1000 elements in a set.

更新於: 2020年3月5日

850 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.