10.3. Copying vectorsΒΆ

There is one more constructor for vectors, which is called a copy constructor because it takes one vector as an argument and creates a new vector that is the same size, with the same elements.

vector<int> copy (count);

Although this syntax is legal, it is almost never used for vectors because there is a better alternative:

vector<int> copy = count;

The = operator works on vectors in pretty much the way you would expect.

Take a look at the active code below, which uses the copy constructor.

Example copying_vectors_AC_1
 1#include <iostream>
 2#include <vector>
 3using std::cout;
 4
 5void print_vec(std::vector<int> vec);
 6
 7int main() {
 8    using std::vector;
 9    vector<int> count = {1,2,3,4};
10    cout << "count = "; print_vec(count);
11
12    vector<int> copy_1 (count);
13    vector<int> copy_2 = count;
14
15    cout << "copy_1 = "; print_vec(copy_1);
16    cout << "copy_2 = "; print_vec(copy_2);
17    cout << "We just made two copies of count.\n"
18         << "As you can see, both methods work the same!\n";
19}

Q1

Multiple Response How would you make a copy of vector<double> decimals called nums?

Q2

What is the name of the function that takes a vector as an argument, and creates a new vector of the same size and with the same elements?