c++中字典的count方法
时间: 2024-04-07 10:33:54 浏览: 21
C++中没有直接称为字典的数据结构,但可以使用std::map或std::unordered_map来实现类似字典的功能。count方法用于统计给定键的出现次数。下面是使用std::map的示例代码:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> dictionary;
// 向字典中添加元素
dictionary["apple"] = 10;
dictionary["banana"] = 5;
dictionary["orange"] = 8;
// 使用count方法统计键的出现次数
if (dictionary.count("apple") > 0) {
std::cout << "apple出现了 " << dictionary.count("apple") << " 次" << std::endl;
} else {
std::cout << "apple未出现" << std::endl;
}
if (dictionary.count("grape") > 0) {
std::cout << "grape出现了 " << dictionary.count("grape") << " 次" << std::endl;
} else {
std::cout << "grape未出现" << std::endl;
}
return 0;
}
```
输出结果:
```
apple出现了 1 次
grape未出现
```
这里使用了`std::map`来创建字典,并使用`count`方法来统计给定键的出现次数。如果键存在,则返回1;如果键不存在,则返回0。