ProgrammingHardProduct-company placement · C++
What is wrong with this loop?
What is wrong with this loop?
vector<int> v{1, 2, 3};
for (int x : v)
if (x == 1) v.push_back(1);- A. Nothing; the loop runs over the original 3 elements only
- B. It loops forever because a 1 is always appended
- C. It fails to compile because v is modified inside a range-for
- D. push_back may reallocate the vector, invalidating the range-for's iterators: undefined behaviour
Correct answer: D. push_back may reallocate the vector, invalidating the range-for's iterators: undefined behaviour
A range-for holds begin/end iterators; growing the vector can move its storage and invalidate them, so continuing the loop is undefined behaviour.
More OOP with C++ and Java questions
- What is printed? cpp void log(int) { cout << "G"; } struct S { void log() { cout << "M"; } void run() { log(5); } }; int main() { S s…
- What happens (C++14)? cpp struct S { static int n; }; int main() { S::n = 1; cout << S::n; }
- Which lines fail to compile? cpp void f(int) { cout << "I"; } void f(double) = delete; int main() { f(5); // L1 f('a'); // L2 f(2.5); //…
- Which lines fail to compile? cpp struct H { static H make() { return new H; } void destroy() { delete this; } private: ~H() { } }; int…
- What is printed? cpp struct B { virtual ~B() { } }; int main() { B p = nullptr; try { cout << typeid(p).name(); } catch (const badtypeid&)…
- What is printed? java class R implements AutoCloseable { String n; R(String n, boolean fail) { if (fail) throw new…