1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. An iterator it points into a std::map. The statement it =…

Added 30 Nov -0001

An iterator it points into a std::map. The statement it = m.erase(it); is executed. What does it hold afterwards?

  1. The value m.begin(), because erasing resets all stored iterators
  2. The iterator to the following element, which erase returned by value Correct answer
  3. An invalidated iterator, so incrementing it afterwards is undefined behaviour
  4. The iterator to the erased element, which remains allocated but detached

Correct answer

B. The iterator to the following element, which erase returned by value

15 views

MCQSEXAM

Explanation

std::map::erase returns an iterator to the element after the erased one, which is the standard erase-while-iterating idiom in C++11 and later. Only iterators to the erased element are invalidated; all others, and every reference, remain valid. The C++03 void-returning erase instead needs the it = m.erase(it++) workaround.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

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