C++ unordered_map count
时间: 2023-10-15 07:29:09 浏览: 62
C++中的`unordered_map`是一个哈希表实现的关联容器,用于存储键值对,并且支持快速的查找操作。`count`函数用于计算某个键在`unordered_map`中出现的次数。
使用方法如下:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> map;
// 添加一些键值对
map["apple"] = 3;
map["banana"] = 2;
map["orange"] = 4;
// 使用count函数计算键的出现次数
std::cout << "Count of apple: " << map.count("apple") << std::endl;
std::cout << "Count of banana: " << map.count("banana") << std::endl;
std::cout << "Count of orange: " << map.count("orange") << std::endl;
std::cout << "Count of grape: " << map.count("grape") << std::endl;
return 0;
}
```
输出结果将是:
```
Count of apple: 1
Count of banana: 1
Count of orange: 1
Count of grape: 0
```
可以看到,`count`函数返回的是一个整数,表示键在`unordered_map`中出现的次数。如果键存在,则返回1,否则返回0。