unordered_map里的count
时间: 2023-10-13 19:18:49 浏览: 39
unordered是C++标准库中的一个容器,用于存储键值对。count函数是unordered_map类的成员函数之一,用于统计特定键的数量。
在unordered_map中,键是唯一的,而值可以重复。count函数接受一个键作为参数,并返回该键在unordered_map中的数量。如果键存在,则返回1;如果键不存在,则返回0。
下面是一个使用unordered_map的count函数的示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> myMap{{1, 10}, {2, 20}, {3, 30}, {4, 40}};
int key = 3;
int count = myMap.count(key);
std::cout << "Count of key " << key << ": " << count << std::endl;
return 0;
}
```
运行该代码将输出:
```
Count of key 3: 1
```
这说明在unordered_map中存在键为3的元素。
相关问题
c++ unordered_map.count
在C++中,`unordered_map.count`是用于统计`unordered_map`容器中某个特定键的出现次数的函数。它返回一个整数值,表示该键在容器中出现的次数。
下面是`unordered_map.count`的使用示例:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 3;
myMap["banana"] = 2;
myMap["orange"] = 5;
int count = myMap.count("apple");
std::cout << "The count of 'apple' is: " << count << std::endl;
return 0;
}
```
输出结果为:
```
The count of 'apple' is: 1
```
unordered_map.count函数
unordered_map.count函数是用来统计给定键值在unordered_map中出现的次数的函数。它返回一个整数,表示给定键值在unordered_map中的出现次数。如果给定键值存在,则返回1,否则返回0。
示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> myMap;
// 向unordered_map中插入键值对
myMap.insert({1, 10});
myMap.insert({2, 20});
myMap.insert({3, 30});
myMap.insert({4, 40});
// 统计键值为2的出现次数
int count = myMap.count(2);
std::cout << "键值为2的出现次数为: " << count << std::endl;
// 统计键值为5的出现次数
count = myMap.count(5);
std::cout << "键值为5的出现次数为: " << count << std::endl;
return 0;
}
```
输出结果:
```
键值为2的出现次数为: 1
键值为5的出现次数为: 0
```