I encountered the following problem:
After I erase a key and a call the key once again from the map, it always returns 0.
So what if the value of a certain key was set to 0?
#include <iostream>#include <map>int main(int argc, char const *argv[]) {std::map<std::string, int> mymap;mymap["a"] = 10;mymap["c"] = 10;mymap["b"] = 20;mymap["zero"] = 0;if (mymap["zero"])std::cout << "yes" << '\n';elsestd::cout << "no" << '\nmymap.erase("zero");if (mymap["zero"])std::cout << "yes" << '\n';elsestd::cout << "no" << '\n';std::cout << mymap["zero"] << '\n';return 0;}
Best Answer
What you need is the count()
function. count()
will return the number of elements and won't construct an object if it doesn't exist. That would make your if statements look like
if (mymap.count("zero"))// key exist here
Since you can use C++17, if you want to do something to the element if found you can leverage it's new if statement syntax that allows you to declare a variable in the if statement and have
if (auto it = mymap.find("zero"); it != mymap.end()){// the element exists and it points to it}
Instead of using if(mymap["key"])
to check if key exists, use .count()
:
if(mymap.count("zero")) { //key exists!...
Your issue here is that the operator[]
will create a new key/value pair if one doesn't exist. From cppreference:
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
So if you try to use mymap["zero"]
to tell if the key "zero"
exists in your map, of course it will--you're creating it!
operator []
of map will insert a new entry with default value. You should use find
instead:
if (mymap.end() != mymap.find(std::string{"zero"}))
There are several options. The easiest one is to check for presence of an element using std::map::find
, rather than operator[]
, which always creates a default value if it is not there.
The other option is put std::optional
as a map data type, and than check if the optional is set.