0

Let's assume I have a map in my code:

map <string, set<string> > myMap;

... and I want to get an element from map:

myMap.find("key");

My question is: what kind of value will myMap return if "key" doesn't exist? `

///EDIT Can anyone point the reason of error? Compiler doesn't see any mistake but server which tests whole algorithm, doesn't accept it because of this function.

    map< string, set<string> >::iterator mapIterator = container.find(key);

    if(mapIterator != container.end()){
        set<string>::iterator setIterator = mapIterator->second.begin();
        if(!mapIterator->second.empty()){
            while(setIterator != mapIterator->second.end()){
                cout << *setIterator << endl;
                ++setIterator;
            }
        }else{
            .......
        }
    }else{
        ..........
    }
RoeJi
  • 31
  • 1
  • 6

4 Answers4

2

It returns an iterator equal to myMap.end(). You can easily test for that:

auto it = myMap.find("key");
if (it == myMap.end())
{
  std::cout << "key not found\n";
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

http://en.cppreference.com/w/cpp/container/map/find

find returns an iterator, so if the key does not exist it returns an end iterator.

eg:

std::map< int, int > some_map;
if ( some_map.find( 10 ) != some_map.end() )
{
  ... key exists ...
}
else
{
  ... key does not exist ...
}
qeadz
  • 1,476
  • 1
  • 9
  • 17
  • Please don't link to cplusplus.com. It is known for inaccuracies and shortcomings. Please use en.cppreference.com for C++ reference – Tony The Lion Apr 17 '14 at 18:46
  • Sure. Changed, although I do like how CPP is organized. Beyond the scope of this question on SO, but I haven't had any issues with the site. I often look up constructors, items in functional or algorithm and so far they've all done what CPP says they do with the parameters that CPP says they have. I guess if it had missed any features, I probably wouldn't realize they're missing. – qeadz Apr 17 '14 at 18:57
0

std::map::find returns iterator (or const_iterator) equal to map.end() if key is not present.

Return value

Iterator to an element with key equivalent to key. If no such element is found, past-the-end (see end()) iterator is returned.

http://en.cppreference.com/w/cpp/container/map/find

Example:

std::map<std::string, int> m;
if( m.find( searchedString) != m.end()) {
   //... present
} else {
   //... not found
}
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

An iterator pointing past the end of the collection. This is true for all stl containers. Check for the value with

map <string, set<string> > myMap;
map <string, set<string> > :: iterator iter = myMap.find( "x" );
if( iter != myMap.end())
{
    // ... do something
}
duncan
  • 446
  • 3
  • 7