[英]How can I check if an element is in map keys in C++?
I am wonder if there is a way I can check if an element is included in map keys. 我想知道是否有一种方法可以检查元素是否包含在地图键中。 For example: 例如:
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<char, int> mymap;
mymap['a'] = 1;
mymap['b'] = 2;
mymap['z'] = 26;
// I want to check if 'b' is one of the keys in map mymap.
return 0;
}
Elements 'a', 'b' and 'z' are the keys of map mymap. 元素“ a”,“ b”和“ z”是地图mymap的键。 I want a command that will return true
if element is in keys of a map and false
if the elements is not in keys of a map. 我想要一个命令,如果元素在地图的键中,则返回true
如果元素不在地图的键中,则返回false
。 I looked around, but could find a quick build-in method that does this. 我环顾四周,但是可以找到一种快速的内置方法来做到这一点。 Did I miss anything? 我有想念吗? Is there a such a method? 有没有这样的方法?
Here is a long way that gets me my desired outcome: 这是让我获得理想结果的长途之路:
#include<iostream>
#include<map>
using namespace std;
bool check_key(map<char, int> mymap, char key_val);
int main()
{
map<char, int> mymap;
mymap['a'] = 1;
mymap['b'] = 2;
mymap['z'] = 26;
char key_val = 'h';
cout<<mymap.find('z')->first<<endl;
cout<<"checking "<< check_key(mymap, 'h')<<endl;
cout<<"checking "<< check_key(mymap, 'b')<<endl;
return 0;
}
bool check_key(map<char, int> mymap, char key_val){
for (map<char, int>::const_iterator it = mymap.begin(); it != mymap.end(); ++it ){
if (key_val == it->first){
return true;
}
}
return false;
}
Thank You in Advance 先感谢您
只需检查是否mymap.find('b') != mymap.end()
。
You can check if a key is present by comparing the result of find()
to the iterator returned by end()
: 您可以通过将find()
的结果与end()
返回的迭代器进行比较来检查是否存在密钥:
std::map<char, int> my_map;
// add items
std::map<char, int>::iterator found = my_map.find('b');
if (found == my_map.end())
{
// 'b' is not in the map
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.