1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. Given a std::map<std::string, int> named counts, what…

Added 30 Nov -0001

Given a std::map&lt;std::string, int&gt; named counts, what happens when counts['alpha'] is evaluated for a key that is not present?

  1. A new element with a value-initialised int of 0 is inserted, so a lookup silently grows the map Correct answer
  2. std::out_of_range is thrown, exactly as counts.at('alpha') would throw for a missing key
  3. A reference to a shared static zero is returned and the map itself is left unmodified
  4. An iterator to the end of the map is returned, and dereferencing it is undefined behaviour

Correct answer

A. A new element with a value-initialised int of 0 is inserted, so a lookup silently grows the map

14 views

MCQSEXAM

Explanation

std::map::operator[] is an inserting lookup: when the key is missing it default-constructs the mapped value, inserts the pair and returns a reference, so even a read can grow the container. That is why it has no const overload and why find() or at() is preferred for pure lookup, at() throwing std::out_of_range instead. The mapped type must therefore be default-constructible, and unordered_map follows exactly the same semantics.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? 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