Prasanth Madhavan
Prasanth Madhavan

Reputation: 13347

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 here 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??

Upvotes: 2

Views: 1702

Answers (8)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361692

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.

Upvotes: 7

Oleg Svechkarenko
Oleg Svechkarenko

Reputation: 2516

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++;
  }

}

Upvotes: 0

Errata
Errata

Reputation: 640

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;
}

Upvotes: 0

Christopher
Christopher

Reputation: 8992

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() )

Upvotes: 1

John Dibling
John Dibling

Reputation: 101494

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

Upvotes: 2

SCFrench
SCFrench

Reputation: 8374

I like b.count(i->first) > 0.

Upvotes: 0

Victor
Victor

Reputation: 348

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())

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

Use map::find().

Upvotes: 3

Related Questions