C++ unordered_map::max_size() 函式



C++ 的 std::unordered_map::max_size() 函式用於返回無序對映或容器可以容納的最大元素數量。此數字取決於系統或庫的實現。

當我們在同一個程式中使用 max_size() 函式處理不同的無序對映或空無序對映時,我們會得到相同的無序對映容器的最大大小。

語法

以下是 std::unordered_map::max_size() 函式的語法。

size_type max_size() const;

引數

此函式不接受任何引數。

返回值

此函式返回一個無符號整數,表示無序對映可以容納的最大元素數量。

示例 1

讓我們來看下面的例子,我們將演示 max_size() 函式的用法。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um;
   cout << "max_size of unordered_map = " << um.max_size() << endl;
   return 0;
}

輸出

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

max_size of unordered_map = 576460752303423487

示例 2

在下面的例子中,我們將對一個空對映進行插入操作,並觀察插入元素前後輸出的變化。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um;
   cout << "max_size of unordered_map = " << um.max_size() << endl;
   um.insert({{'A', 2}, {'B', 5}, {'C', 6}, {'D', 10}});
   cout<<"*** Maximum size of unordered map after inserting the element to it ***"<<endl;
   cout << "max_size of unordered_map = " << um.max_size() << endl;
   return 0;
}

輸出

以下是上述程式碼的輸出:

max_size of unordered_map = 576460752303423487
*** Maximum size of unordered map after inserting the element to it ***
max_size of unordered_map = 576460752303423487

示例 3

考慮下面的例子,我們將考慮兩個不同大小的對映,並檢查兩個容器的最大大小是否相同或不同。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<int, int> uMap;
   unordered_map<int, int> um;
   cout << "max_size of unordered_map = " << uMap.max_size() << endl;
   cout << "max_size of unordered_map = " << um.max_size() << endl;
   uMap.insert({{1, 2}, {2, 5}, {3, 6}, {4, 10}});
   um.insert({{2, 2}, {3, 5}, {5, 6}, {6, 10}});
   cout<<"*** Maximum size of unordered map after inserting the element to it ***"<<endl;
   cout << "max_size of unordered_map = " << uMap.max_size() << endl;
   cout << "max_size of unordered_map = " << um.max_size() << endl;
   return 0;
}

輸出

上述程式碼的輸出如下:

max_size of unordered_map = 576460752303423487
max_size of unordered_map = 576460752303423487
*** Maximum size of unordered map after inserting the element to it ***
max_size of unordered_map = 576460752303423487
max_size of unordered_map = 576460752303423487
廣告