LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 19

Copying a vector vs referring to it Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> a{1, 2, 3};
    std::vector<int> b = a;
    std::vector<int>& c = a;
    b[0] = 100;
    c[1] = 200;
    std::cout << a[0] << ' ' << a[1] << ' ' << b[1] << ' ' << c.size() << '\n';
    return 0;
}
  • A 1 200 2 3 Correct
  • B 100 200 2 3
  • C 1 2 2 3
  • D 1 200 200 3
Correct Answer: Option A

b is an independent copy, so changing it leaves a alone. c is another name for a, so c[1] = 200 changes a.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links