unordered_map count函数
时间: 2023-04-23 13:00:09 浏览: 101
`unordered_map` 是 C++ 中的一种无序映射容器,它可以用来存储键值对。`count` 函数用来统计给定键在 `unordered_map` 中出现的次数。如果该键不存在,则返回 0;否则返回键的数量。例如:
```
unordered_map<string, int> mymap;
mymap["apple"] = 10;
mymap["banana"] = 20;
int apple_count = mymap.count("apple"); // apple_count = 1
int orange_count = mymap.count("orange"); // orange_count = 0
```
相关问题
c++unordered_map count
unordered_map 是 C++ STL 中的一个关联容器,用于存储键值对。count 函数用于返回指定键在容器中出现的次数,因为 unordered_map 中每个键只能出现一次,所以 count 函数的返回值只能是 0 或 1。
下面是一个使用 unordered_map count 函数的示例代码:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
std::cout << "apple count: " << myMap.count("apple") << std::endl;
std::cout << "grape count: " << myMap.count("grape") << std::endl;
return 0;
}
```
输出结果为:
```
apple count: 1
grape count: 0
```
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
```