将`std :: copy()`与`std :: back_inserter()`一起使用 [英] Using `std::copy()` with `std::back_inserter()`
问题描述
我有两个班级A和B,都有一个成员,如下所示:
I have two class A and B both have a member like below:
class A {
...
std::vector<std::vector<std::vector<size_t>>> grid;
}
class B {
...
std::vector<std::vector<std::vector<size_t>>> grid;
}
我发现当我使用 std :: copy()
从 A :: grid
复制到 B :: grid
时,它将失败.这是我的工作:
I found when I use std::copy()
to copy from A::grid
to B::grid
, it will fail.
Here is what I do:
// Here is in B's constructor.
// I initialize B::grid with the same size of A::grid
grid = vector<vector<vector<size_t>>>(GetSetting().grid_cols());
for (int i = 0; i < GetSetting().grid_cols(); i++) {
grid[i] = vector<vector<size_t>>(GetSetting().grid_rows());
for (int j = 0; j < GetSetting().grid_rows(); j++) {
grid[i][j].reserve(a.grid[i][j].size());
}
}
// Copy from A to B
std::copy(a.grid.begin(), a.grid.end(), std::back_inserter(grid));
但是,如果我删除了初始化部分,那么std :: copy将可以正常工作.初始化部分怎么了?
But if I remove initialize part, then the std::copy will work fine. What's wrong for the initialize part?
推荐答案
让我为您展示一个简化的示例.
Let me show you with a simplified example.
std::vector<int> v = {1, 2, 3};
std::vector<int> v1;
std::copy(v.begin(), v.end(), std::back_inserter(v1));
在这种情况下,v1将按预期为1、2、3.现在考虑一下:
In this scenario v1 will be 1, 2, 3, as expected. Now consider this:
std::vector<int> v = {1, 2, 3};
std::vector<int> v1(3); //v1 has initial size!!
std::copy(v.begin(), v.end(), std::back_inserter(v1));
现在v1将为0、0、0、1、2、3,因为 back_inserter
push_back
s.如果您已经在目标中分配了必要的大小,请使用 begin()
迭代器,而不要使用 back_insert_iterator
:
Now v1 will be 0, 0, 0, 1, 2, 3, because back_inserter
push_back
s. If you have already allocated the necessary size in the destination, then use the begin()
iterator and not the back_insert_iterator
:
std::vector<int> v = {1, 2, 3};
std::vector<int> v1(3); //v1 has initial size!!
std::copy(v.begin(), v.end(), v1.begin()); //use begin here
v1符合预期,是1,2,3.
v1 is 1, 2, 3, as expected.
这篇关于将`std :: copy()`与`std :: back_inserter()`一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!