Reputation: 171
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);
Upvotes: 0
Views: 347
Reputation: 17474
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.
Upvotes: 5