底层STL:将std :: vector连接到自身而没有新的向量

问题描述:

我有一个STL向量存储矩阵的对角线。我实现的某个数学规则告诉我,我可以通过取原始向量并将该向量的副本连接到自身上来生成张量积对角线的新矩阵(它的大小加倍,并且值在1 / 2 * size())。

I have an STL vector that stores the diagonals of a matrix. A certain mathematical rule I'm implementing tells me that I can produce a new matrix of a tensor product's diagonals simply by taking the original vector and concatenating a copy of that vector onto itself (it doubles in size, and the values repeat after 1/2 * size() ).

我写了以下代码:

std::vector<int> aVec;

for (int k = 0; k < aVec.size(); k++) aVec.insert(aVec.end(), aVec[k]);

但是当我尝试这个时,我得到seg-faults。如果我创建一个aVec的副本,并使用它作为插入值,以及使用它的size()在循环args,它会工作,但我必须这两个

But I get seg-faults when I try this. If I create a copy of aVec and use that as the insert "value", as well as using it for the size() in the loop args, it will work, but I must do both of these things (otherwise I will still get seg-faults).

任何人都可以解释下面发生了什么使得这个实现无法正常工作?

Can anyone explain what's going on underneath that makes this implementation not work?

您将无限期地复制项目。注意前面要复制的数量:

You will copy items indefinitely. Note how many to copy up front:

size_t n = aVec.size();
for (int k = 0; k != n; ++k)
  aVec.push_back(aVec[k]);

虽然许多C ++算法使用 begin() end()迭代器,在这种情况下,通过索引访问是优越的,因为修改容器可能使迭代器无效,但元素访问将保持有效。但是,您可以使用 reserve 避免无效:

While many C++ algorithms are better expressed using begin() and end() iterators, in this case your access via index is superior, because modifying the container might invalidate the iterators, but the element access will remain valid. You can, however, use reserve to avoid that invalidation:

aVec.reserve(2*aVec.size());
std::copy(aVec.begin(), aVec.end(), std::back_inserter(aVec));