简体   繁体   English

.push_back 如何在 C++ 中工作?

[英]How .push_back works in C++?

I have a question in my mind.我心里有个问题。 Lets say I have two vectors called vector1 and vector2.假设我有两个向量,称为vector1 和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_2d 的二维向量,并使用 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? C++ 如何决定将vector2分配给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.我还尝试将vector1多次添加到一个名为new_vector的新二维向量中。 But it seems to be add vector1 only once.但似乎只添加了一次vector1。 Why is this the case?为什么会这样? Why it didn't add multiple vector1 to new rows or back to back?为什么它没有将多个 vector1 添加到新行或背靠背?

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);

How C++ decides to assign the vector2 to the second row of the vector_2d? C++ 如何决定将vector2分配给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.这就是在外部向量上调用push_back时发生的情况。

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.我还尝试将vector1多次添加到一个名为new_vector的新二维向量中。 But it seems to be add vector1 only once.但似乎只添加了一次vector1。 Why is this the case?为什么会这样?

It isn't.它不是。

Why it didn't add multiple vector1 to new rows or back to back?为什么它没有将多个 vector1 添加到新行或背靠背?

It did.它做了。 You must have observed it wrong somehow.你一定以某种方式观察到了错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM