🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Iterators in C++: all 10 questions

Quiz: Iterators in C++ · Question 5 of 10

Which loop correctly removes all even numbers from a vector v while iterating?

Which loop correctly removes all even numbers from a vector v while iterating?

  1. A.for (auto it = v.begin(); it != v.end(); ++it) if (*it % 2 == 0) v.erase(it);
  2. B.for (auto it = v.begin(); it != v.end(); ) { if (*it % 2 == 0) it = v.erase(it); else ++it; }
  3. C.for (int x : v) if (x % 2 == 0) v.erase(x);
  4. D.for (auto it = v.end(); it != v.begin(); --it) v.erase(it);
Answer & explanation

Correct answer: for (auto it = v.begin(); it != v.end(); ) { if (*it % 2 == 0) it = v.erase(it); else ++it; }

erase invalidates the old iterator and returns the next valid one, which must be used.

Can you get the rest right without peeking?

Take the timed Quiz: Iterators in C++ quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →