c++ unordered_map的count
时间: 2023-11-09 11:08:19 浏览: 86
unordered_map是C++ STL中的一个关联容器,用于存储键值对。count函数用于返回指定键在容器中出现的次数,因为unordered_map中每个键都是唯一的,所以count函数返回值只能是0或1。
示例代码:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
// 判断键是否存在
if (myMap.count("apple")) {
std::cout << "apple exists in myMap" << std::endl;
} else {
std::cout << "apple does not exist in myMap" << std::endl;
}
if (myMap.count("pear")) {
std::cout << "pear exists in myMap" << std::endl;
} else {
std::cout << "pear does not exist in myMap" << std::endl;
}
return 0;
}
```
输出:
```
apple exists in myMap
pear does not exist in myMap
```
阅读全文