在C++中,可以使用map的count()函数或者find()函数来查找key是否存在。
使用count()函数:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
if (myMap.count(2) > 0) {
std::cout << "Key 2 exists in the map" << std::endl;
}
else {
std::cout << "Key 2 does not exist in the map" << std::endl;
}
return 0;
}
使用find()函数:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
if (myMap.find(2) != myMap.end()) {
std::cout << "Key 2 exists in the map" << std::endl;
}
else {
std::cout << "Key 2 does not exist in the map" << std::endl;
}
return 0;
}
上述两种方法都可以判断key是否存在于map中。count()函数返回key在map中出现的次数,而find()函数返回指向key所在位置的迭代器。如果find()函数返回的迭代器等于map.end(),则表示key不存在于map中。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C++中ICMP协议如何实现