c++ map的count
时间: 2023-11-12 13:00:51 浏览: 117
C++中的map是一种关联容器,它将键映射到值。count()函数用于返回指定键在map中出现的次数,因为map中每个键只能出现一次,所以count()函数的返回值只能是0或1。
例如,我们有一个map<string, int>,我们可以使用count()函数来检查某个键是否存在于map中:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> myMap;
myMap["apple"] = 1;
myMap["banana"] = 2;
myMap["orange"] = 3;
if (myMap.count("apple")) {
cout << "apple exists in the map" << endl;
} else {
cout << "apple does not exist in the map" << endl;
}
if (myMap.count("pear")) {
cout << "pear exists in the map" << endl;
} else {
cout << "pear does not exist in the map" << endl;
}
return 0;
}
```
输出结果为:
```
apple exists in the map
pear does not exist in the map
```
阅读全文