how can I check whether a key is present in a variable of map data-structure or not in c++? The following code snippet describes my map variable
map<int,int> m;
you can also use m.find() map iterator to find whether the key is present or not. If the value is not present then this iterator must equals m.end(). As used in the code snippet below
map<int,int> m; m.insert(pair<int,int>(6,9)); int key=5; if(m.find(key)!=m.end()){ //key is present in the map }else{ //key is not present in the map }
there are different ways, you can use m.count() method to check whether the key exists or not. As map contains unique keys so count will be 0 if not present or 1 if present.
map<int,int> m; m.insert(pair<int,int>(6,9)); int key=5; if(m.count(key)>0){ //present in map }else{ //not present in map }
you can alternatively use m.count(key)==1 or m.count(key)!=0 in place of m.count(key)>0