0
votes

I have a question in my mind. Lets say I have two vectors called vector1 and vector2.

vector <int> vector1{1,2};
vector <int> vector2{3,4};

Now I want to create a 2-D vector called vector_2d and assign these two vectors into my new 2-D vector using push_back function.

vector <vector <int>> vector_2d;
vector_2d.push_back(vector1);
vector_2d.push_back(vector2);

How C++ decides to assign the vector2 to the second row of the vector_2d? Why it didn't add these two vectors back to back?

Also I tried to add the vector1 multiple times to a new 2-D vector called new_vector. But it seems to be add vector1 only once. Why is this the case? Why it didn't add multiple vector1 to new rows or back to back?

vector <vector <int>> new_vector;
new_vector.push_back(vector1);
new_vector.push_back(vector1);
new_vector.push_back(vector1);
new_vector.push_back(vector1);
1
How do you know that it only added vector1 once? How did you measure that? - user253751
push_back == push onto the back. - NathanOliver
"Why it didn't add multiple vector1 to new rows or back to back?" You do exactly that. You add a copy of the vector1 to the back of new_vector - Klaus
I dont understand the question - Sebastian Hoffmann
Please run your program under a debugger and inspect new_vector. It will give you a better understanding of the resulting object structure than printing ever can. - Botje

1 Answers

5
votes

How C++ decides to assign the vector2 to the second row of the vector_2d?

By reading your code.

You're adding two "inner" vectors to your outer vector, resulting in two elements.

That's what happens when you call push_back on the outer vector.

Why it didn't add these two vectors back to back?

Because you didn't tell it to.

That would be:

vector <vector <int>> vector_2d;
vector_2d.push_back(vector1);
std::copy(std::begin(vector2), std::end(vector2), std::back_inserter(vector_2d[0]));

Also I tried to add the vector1 multiple times to a new 2-D vector called new_vector. But it seems to be add vector1 only once. Why is this the case?

It isn't.

Why it didn't add multiple vector1 to new rows or back to back?

It did. You must have observed it wrong somehow.