通过移动将向量附加到另一个向量(pre C++11)

Append vector to another with a move (pre C++11)

本文关键字:向量 另一个 pre C++11 移动      更新时间:2023-10-16

我正在处理一些相对较大的整数向量,我有一个顶级向量,我需要将其他(临时)向量的结果累积到其中。

遗憾的是,将其

扩展到原地不是一种选择,因为我从另一个 API 收到预先准备好的临时向量,并且出于同样的原因,我被困在 GCC 4.1.2 上,所以没有一个好的移动语义或 std::move 的 C++11。

目前我正在使用插入进行复制,例如:

vector<int> accumulator;
for(){
    vector<int> tempVector = vectReturningFunction();
    ...
    if(!tempVector.empty()){
        accumulator.insert(accumulator.end(), tempVector.begin(), tempVector.end());
    }
}

由于 temp 通常是一次性的,并且数据可能足够大,我希望能够移动而不是复制,但我无法找到一种优雅的方法。

任何解决方案,甚至只是指向有用方向的指针(没有双关语),将不胜感激。我还模糊地记得几年前读过Stroustrup在C++11之前的一个食谱,可以跨STL容器移动,但是现在有太多C++11的东西,没有提供多少搜索。

谢谢。

您也无法在 C++11 中移动矢量内容。移动语义仅适用于向量的元素,但由于元素是int因此没有任何好处。你想要的是不可能的。但是如果你想避免合并,你可以存储一个向量的向量:

vector< vector<int> > accumulator;
accumulator.reserve(expectedCount); // reserve some space so that you avoid copying contents on vector resizing.
for(/*...*/){
    accumulator.resize(accumulator.size()+1); // make space for a new vector
    vectReturningFunction().swap(accumulator.back()); // just swap no copy of the vector
}

这完全取决于您想用累加器做什么。如果你真的需要有一个vector<int>,那么在最后合并向量比一个接一个地附加它们可能仍然更便宜。

避免复制数据(和重新分配)的唯一方法是不带 C++11,是累积到vector<vector<int>>

std::vector<std::vector<int>> accumulator;
for(){
    // C++03
    accumulator.resize(accumulator.size()+1);
    vectReturningFunction().swap(accumulator.back()); // Juraj
    if(accumulator.back().empty())
        accumulator.resize(accumulator.size()-1);
    // C++11
    // auto temp = vectReturningFunction();
    // if(!temp.empty())
    //     accumulator.push_back(std::move(temp));
}