方法
用find函数,会返回一个迭代器,如果迭代器指向了map的尾部,则可以判定不存在这个元素;否则,就存在;
代码写法
- 单独一个函数;
- 用lambda函数的方式写在需要用到的位置;
代码
#include <iostream>
#include <vector>
#include <map>
bool checkExist(const std::map<std::string, int>& map, const std::string& key){
auto temp = map.find(key);
if(temp == map.end()){
std::cout << "not found" << std::endl;
return false;
}
std::cout << "found" << std::endl;
return true;
}
int main() {
std::map<std::string, int> map;
std::string key1 = "1234";
map[key1] = 1;
auto checkExistFunc = [&](const std::string& key) -> bool {
auto temp = map.find(key);
return (temp == map.end() ? false : true);
};
// checkExist(map, "1234");
checkExistFunc("1234");
return 0;
}