C++ unordered_set::max_size() 函式



C++ 的 std::unordered_set::max_size() 函式用於返回 unordered_set 容器由於系統和庫實現限制可以容納的最大元素數量。

在特定程式中,最大大小始終相同;它不取決於 unordered_set 的大小或型別,也不取決於 unordered_set 是否為空。

語法

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

size_type max_size() const noexcept;

引數

此函式不接受任何引數。

返回值

此函式返回 unordered_set 容器可以容納的最大元素數量。

示例 1

考慮以下示例,我們將演示 unordered_set::max_size() 函式的用法。

#include <iostream>
#include <string>
#include <unordered_set>

int main () {
   std::unordered_set<std::string> myset;
   std::cout << "0. size: " << myset.max_size() << std::endl;

   myset = {"milk","potatoes","eggs"};
   std::cout << "1. size: " << myset.max_size() << std::endl;

   myset.insert ("pineapple");
   std::cout << "2. size: " << myset.max_size() << std::endl;

   myset.erase ("milk");
   std::cout << "3. size: " << myset.max_size() << std::endl;

   return 0;
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

0. size: 768614336404564650
1. size: 768614336404564650
2. size: 768614336404564650
3. size: 768614336404564650

示例 2

讓我們來看一下下面的示例,我們將使用 unordered_set::max_size() 函式來獲取容器可以容納的最大大小。

#include <iostream>
#include <iostream>
#include <locale>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<int> uSet = {1, 2, 3};
   // Check if the locale is available on the system
   try {
      cout.imbue(locale("en_US.UTF-8"));
   } catch (const std::runtime_error& e) {
      cout << "Locale not found: " << e.what() << '\n';
      // Fallback to the default locale
      cout.imbue(locale(""));
   }
   cout << "Maximum size of an unordered_set is " << uSet.max_size() << '\n';
   return 0;
}

輸出

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

Locale not found: locale::facet::_S_create_c_locale name not valid
Maximum size of an unordered_set is 576460752303423487

示例 3

在下面的示例中,我們將考慮包含整數型別的 unordered_set,並應用 unordered_set::max_size() 函式來顯示兩個 unordered_set 的最大大小。

#include <iostream>
#include <locale>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<int> uSet, myUset;
   uSet={1, 2, 3};
   myUset={2, 3, 4, 5};
   cout << "Maximum size of a unordered_set first is " << uSet.max_size() << '\n';
   cout << "Maximum size of a unordered_set second is " << myUset.max_size() << '\n';
}

輸出

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

Maximum size of a unordered_set first is 576460752303423487
Maximum size of a unordered_set second is 576460752303423487

示例 4

以下是 unordered_set::max_size() 函式用法的另一個示例,我們將考慮兩個 unordered_set,一個是 int 型別,另一個是 char 型別,並顯示兩個 unordered_set 的最大大小。

#include <iostream>
#include <locale>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<int> uSet = {1, 2, 3};
   unordered_set<char> myUset = {'a', 'b', 'c'};
   cout << "Maximum size of a unordered_set first is " << uSet.max_size() << '\n';
   cout << "Maximum size of a unordered_set second is " << myUset.max_size() << '\n';
}

輸出

上述程式碼的輸出如下:

Maximum size of a unordered_set first is 576460752303423487
Maximum size of a unordered_set second is 576460752303423487
廣告