tags:

views:

376

answers:

4

Hi, I'm trying to check if value is in a map and somewhat can't do it:

typedef map<string,string>::iterator mi;
    map<string, string> m;
    m.insert(make_pair("f","++--"));
    pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want
    cout << p.first;//I'm getting error here

so how can I print what is in p? Thank you

+3  A: 

You can use .find():

map<string,string>::iterator i = m.find("f");

if (i == m.end()) { /* Not found */ }
else { /* Found, i->first is f, i->second is ++-- */ }
Andreas Bonini
+4  A: 

I think you want map::find. If m.find("f") is equal to m.end(), then the key was not found. Otherwise, find returns an iterator pointing at the element found.

The error is because p.first is an iterator, which doesn't work for stream insertion. Change your last line to cout << (p.first)->first;. p is a pair of iterators, p.first is an iterator, p.first->first is the key string.

A map can only ever have one element for a given key, so equal_range isn't very useful. It's defined for map, because it's defined for all associative containers, but it's a lot more interesting for multimap.

Steve Jessop
Actually, because it is a pair of iterators to a map, it should be "cout << p.first->first;"
stefaanv
I've fixed my answer, thanks. That's what I get for not compiling my code. And you're right (in a deleted comment) about checking for validity, but I was just trying to explain why he couldn't print p.first, and it's not because it's invalid - we know "f" will be found. Since I don't recommend using equal_range at all, I'm not about to show error-checking code for that.
Steve Jessop
Wow, you're really scanning SO. I was just adding it for completeness, because your point was clear. I added the validity check to my previous answer, but your response beated me, so I deleted it, because it didn't add that much anyway, as you mentioned.
stefaanv
Yes, I only saw it at all because your comment appeared when I posted mine.
Steve Jessop
+13  A: 

What is wrong with find:

if ( m.find( "f") == m.end() ) {
  // not found
}
else {
  // found
}
anon
Thanks, rest is just to fill 15 char requierment.
There is nothing we can do
I'm feckin' eejit (how could I not think of find()?), my thinking is somewhat slower than usual.
There is nothing we can do
+1  A: 
m.find == m.end() // not found

If you want to use other API, then find go for m.count(c)>0

 if (m.count("f")>0)
      cout << " is an element of m.\n";
    else 
      cout << " is not an element of m.\n";
aJ