How to see if a key is present in a map?
I hav two stl maps like map<int,int>
and i want to compare them.. so he开发者_如何学Pythonre is the code..
map <int, int> a,b;
insert into a and b;
map<int,int>::iterator i;
for(i=a.begin();i!=a.end();i++){
if(what should be here?)
then cout << (*i).first << " also present in b" << endl;
}
I was hoping that something like (b[(*i).first]).exist??
Use map::find
as:
for(i=a.begin(); i!=a.end(); i++)
{
if( b.find(i->first) != b.end() )
std::cout << (*i).first << " also present in b" << std::endl;
}
Note i->first
and (*i).first
are same.
Use map::find()
.
This will return true if i->first (the key of the element in a pointed by i) is present in b.
if (b.find(i->first) != b.end())
You can't use operator[]
, because that will create the key if it doesn't exist. Instead, use find
:
map<int,int>::const_iterator it = b.find(a->first);
if( it == b.end() )
// NOT FOUND
std::map has a function named find for finding a key in the map. See this
So the code should be :
if( b.find( i->first ) != b.end() )
I like b.count(i->first) > 0
.
map::find function
I will do as this :
std::map <int, int> a,b;
insert into a and b;
std::map<int,int>::iterator it = a.begin();
std::map<int,int>::iterator ite = a.end();
while (it != ite)
{
if (b.find(it->first) != b.end())
{
std::cout << it->first << " also present in b" << std::endl;
}
++it;
}
For your task for performance reasons I would suggest something like:
map<int,int>::iterator ia = a.begin(), ib = b.begin(),
iae = a.end() , ibe = b.end();
while(ia != iae && ib != ibe) {
if (ia->first < ib->first) ia++;
else if (ia->first > ib->first) ib++;
else {
cout << ia->first << " also present in b" << endl;
ia++; ib++;
}
}
精彩评论