C++ List::max_size() 函式



C++ 的std::list::max_size()函式用於獲取列表的最大大小。

它返回當前列表可以容納的最大元素數(或最大大小)。換句話說,它檢索容器可以達到的最大大小,但是,不能保證它可以分配該大小的元素,並且仍然可能無法為列表容器的特定點分配儲存空間。此值取決於系統或庫的實現。

語法

以下是 C++ std::list::max_size() 函式的語法:

size_type max_size();

引數

  • 它不接受任何引數。

返回值

此函式返回可以放入列表中的最大數字。

示例 1

如果列表是 int 型別。

在下面的程式中,我們使用 C++ std::list::max_size() 函式獲取名為 num_list 的當前列表的最大大小。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list;
   cout<<"Size of the list: "<<num_list.size()<<endl;
   cout<<"The max_size of list = "<<num_list.max_size()<<endl;
   return 0;
}

輸出

執行上述程式後,將產生以下輸出:

Size of the list: 0
The max_size of list = 384307168202282325

示例 2

查詢 char 型別列表的最大大小。

以下是 C++ std::list::max_size() 函式的另一個示例。在這裡,我們建立了一個名為 char_list 的列表(型別為 char),其值為 {'a', 'b', 'c', 'd'}。然後,使用 max_size() 函式,我們嘗試查詢當前列表的最大大小。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<char> char_list = {'a', 'b', 'c', 'd'};
   cout<<"Size of the list: "<<char_list.size()<<endl;
   cout<<"List elements are: "<<endl;
   for(char c: char_list) {
      cout<<c<<" ";
   }
   cout<<"\nThe max_size of list = "<<char_list.max_size()<<endl;
   return 0;
}

輸出

以下是上述程式的輸出:

Size of the list: 4
List elements are: 
a b c d 
The max_size of list = 384307168202282325

示例 3

除了 int 型別和 char 型別列表之外,您還可以找到 string 型別列表的最大大小。

在此示例中,我們建立了一個名為 str_list 的列表(型別為 string),其值為 {"Java", "C++", "Python", "Apex"}。然後,使用 max_size() 函式,我們嘗試查詢此列表的最大大小。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<string> str_list = {"Java", "C++", "Python", "Apex"};
   cout<<"Size of the list: "<<str_list.size()<<endl;
   cout<<"List elements are: "<<endl;
   for(string s: str_list) {
      cout<<s<<" ";
   }
   cout<<"\nThe max_size of list = "<<str_list.max_size()<<endl;
   return 0;
}

輸出

這將生成以下輸出:

Size of the list: 4
List elements are: 
Java C++ Python Apex 
The max_size of list = 192153584101141162
廣告

© . All rights reserved.