← 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?
- A.for (auto it = v.begin(); it != v.end(); ++it) if (*it % 2 == 0) v.erase(it);
- B.for (auto it = v.begin(); it != v.end(); ) { if (*it % 2 == 0) it = v.erase(it); else ++it; }
- C.for (int x : v) if (x % 2 == 0) v.erase(x);
- 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 →