-3

I have the following map in c++

std::map<string,int> mymap;

after inserting several values into it I then want to be able to search for a value in the map. I can use the find function to accomplish this

std::cout << "a => " << mymap.find("a")->second << '\n';

The problem with this is that find returns 0 when I search for a key that doesn't exist. I may want to insert a key with a value of 0 but I also need to know if a certain key does not exist in the map. Is there any way to accomplish this?

Murphstar
  • 99
  • 6
  • `find` does not return 0 if the key doesn't exist. It returns `end()`. You need to check for that and handle it separately. – alter_igel Mar 08 '19 at 21:56

1 Answers1

1

std::map::find is not doing what you think it's doing.

When you call find on a key that does not exist, the iterator returned is an invalid iterator; it does not point to a valid object. So any operations you attempt to perform on this object is undefined behavior, and (probably) an access to invalid memory.

The way you should be using find is to take the iterator and compare it to the map's end iterator to make sure it's valid.

std::map<std::string, int> mymap;

if(auto it = mymap.find("a"); it != mymap.end()) {//C++17 Initialized-If statement syntax
    std::cout << "a => " << it->second << std::endl;
}

//Old Syntax
std::map<std::string, int> mymap;

auto it = mymap.find("a"); 
if(it != mymap.end()) {
    std::cout << "a => " << it->second << std::endl;
}
Community
  • 1
  • 1
Xirema
  • 19,889
  • 4
  • 32
  • 68