[英]Using `std::copy()` with `std::back_inserter()`
I have two class A and B both have a member like below: 我有两个A级和B级都有如下成员:
class A {
...
std::vector<std::vector<std::vector<size_t>>> grid;
}
class B {
...
std::vector<std::vector<std::vector<size_t>>> grid;
}
I found when I use std::copy()
to copy from A::grid
to B::grid
, it will fail. 我发现当我使用
std::copy()
从A::grid
复制到B::grid
,它会失败。 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));
But if I remove initialize part, then the std::copy will work fine. 但是,如果我删除初始化部分,那么std :: copy将正常工作。 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));
In this scenario v1 will be 1, 2, 3, as expected. 在这种情况下,v1将如预期的那样为1,2,3。 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));
Now v1 will be 0, 0, 0, 1, 2, 3, because back_inserter
push_back
s. 现在v1将是
back_inserter
,因为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
: 如果已在目标中分配了必要的大小,则使用
begin()
迭代器而不是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 is 1, 2, 3, as expected. 按预期,v1为1,2,3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.