What happens when std::map is indexed with operator[] using a key that is not present?
Correct answer
D. A default-constructed value is inserted for that key
16 views
D. A default-constructed value is inserted for that key
16 views
std::map::operator[] inserts a new entry with a value-initialised mapped type when the key is absent, then returns a reference to it, so a lookup can silently change the container. at() throws std::out_of_range instead, and find() returns end() without modifying the map. This is why counting loops often use ++counts[key], which relies on the default value being zero.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.