C++ unordered_map::size() 函式



C++ 的std::unordered_map::size()函式用於返回無序對映中存在的元素數量。如果無序對映不包含任何元素,則size()函式返回0。

語法

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

size_type size() const noexcept;

引數

此函式不接受任何引數。

返回值

此函式返回無序對映容器中實際存在的元素數量。

示例 1

在以下示例中,讓我們演示 unordered_map::size() 函式的用法。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um;
   cout << "Initial size of unordered map = " << um.size() << endl;
   um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Size of unordered map after inserting elements = " << um.size() << endl;
   return 0;
}

輸出

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

Initial size of unordered map = 0
Size of unordered map after inserting elements = 5

示例 2

以下是一個示例,我們將建立一個儲存整數型別鍵值對的無序對映,並應用 size() 函式來獲取當前無序對映中存在多少個元素。

#include <unordered_map>
#include <iostream>
using namespace std;
int main() { 
   unordered_map<int,int> nums {{1, 10}, {3, 30}, {5, 50}, {7, 70}};
   cout << "nums contains " << nums.size() << " elements.\n";
}

輸出

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

nums contains 4 elements.

示例 3

讓我們看一下下面的例子,我們將找到偶數鍵及其值,將它們儲存到另一個容器中,並應用 size() 函式來查詢元素的數量。

#include <unordered_map>
#include <iostream>
using namespace std;
int main() { 
   unordered_map<int,int> uMap {{1, 5}, {2, 30}, {3, 50}, {4, 70}, {5, 10}, {6, 20}};
   unordered_map <int, int> nums;
   for(auto & it:uMap){
      if(it.first % 2 == 0){
         nums.insert({it.first, it.second});
      }
   }
   cout<<"total even key in nums unordered_map: "<<nums.size()<<endl;
   return 0;
}

輸出

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

total even key in nums unordered_map: 3
廣告