check the size of key/index that doesn't exist?

I have a map <int, vector <string>> mymap

Is it safe to check the size of key/index that doesn't exist?

Lets say index 24 is not created, then...

if(mymap[24].size() > 10)

Can this cause undefined behavior or maybe add a value to it etc?
Last edited on
http://www.cplusplus.com/reference/map/map/operator[]
If k does not match the key of any element in the container, the function inserts a new element with that key

https://en.cppreference.com/w/cpp/container/map/operator_at
Inserts value_type(key, T()) if the key does not exist.
Last edited on
1
2
3
4
if (!mymap[24].size()) {
   cout << mymap[24].size(); //then why is this still zero if new element is added?
}
	
As soon as you checked if (!mymap[24].size()), mymap had a new entry placed in it. The entry maps the key "10" to a value of vector<string>. Because you used operator[], the default constructor of vector<string> was called, which provides an empty vector.

So, mymap[24] returns a reference to an empty vector<string>. Because the vector is empty, the size() of the vector is 0.

The map is one element larger, but you never checked the map's size. You only checked the size of the vector at mymap[24].
You can check, whether key/element exists:
http://www.cplusplus.com/reference/map/map/count/
1
2
3
if ( mymap.count(24) > 0 && mymap[24].size() > 10 ) {
  // something
}
Topic archived. No new replies allowed.