map::count

Aug 2, 2010 at 11:21pm
If the map is like

std::map<int, std::string> myMap
myMap[1]="ab"
myMap[2]="bb"
myMap[3]="ba"

I have to check if a string is present in the map or not
myMap.count() wont work..Can anyone tell me how can I for example check if "bb" exist in the map or not
Thanks
Aug 2, 2010 at 11:28pm
Aug 3, 2010 at 12:54am
find and count operates on the key, not the value.
You can try this
1
2
3
4
for(it=m.begin(); it!=m.end(); it++)
    if(it->second == value)
        return true;
return false;

Aug 3, 2010 at 12:24pm
Is there any other way as I have to use it a couple of times and its making my program really slow
Aug 3, 2010 at 1:12pm
Option 1. Change it to std::map< std::string, int >.

Option 2. Use boost::multi_index_container<>.

Aug 3, 2010 at 1:13pm
You could keep a parallel std::set<> with all your values in.
Aug 3, 2010 at 2:07pm
I've recently become an advocate of boost::multi_index_container. It would be perfect for this.

Anyway, here are some practical thoughts about your problem:

1. First of all, unless you really need the integer key, consider just using a std::set<std::string>.

2. You could create a small predicate functor and pass it to std::find_if. Note that this would be O(n) lookup.
Last edited on Aug 3, 2010 at 2:08pm
Topic archived. No new replies allowed.