C++ unordered_map::size() 函数



C++ 的std::unordered_map::size()函数用于返回无序映射中存在的元素数量。如果无序映射不包含任何元素,则size()函数返回0。

语法

以下是 std::unordered_map::size() 函数的语法。

size_type size() const noexcept;

参数

此函数不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回无序映射容器中实际存在的元素数量。

示例 1

在以下示例中,让我们演示 unordered_map::size() 函数的用法。

Open Compiler
#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() 函数来获取当前无序映射中存在多少个元素。

Open Compiler
#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() 函数来查找元素的数量。

Open Compiler
#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
广告