1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. What happens when std::map is indexed with operator[]…

Added 30 Nov -0001

What happens when std::map is indexed with operator[] using a key that is not present?

  1. An exception of type std::out_of_range is thrown at once
  2. A null reference is returned to the caller
  3. The call fails to compile for missing keys
  4. A default-constructed value is inserted for that key Correct answer

Correct answer

D. A default-constructed value is inserted for that key

16 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs