Search code examples
c++movestdvector

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


I'm handling some relatively large vectors of ints, and I have one top level vector that I need to accumulate the results of other (temporary) vectors into.

Extending it in place is sadly not an option as I receive the temporary vectors pre-cooked from another API, and I'm stuck with GCC 4.1.2 for the same reason, so none of the nice move semantics or std::move of C++11.

Currently I'm copying with insert, something like:

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

As temp is routinely disposable and the data can be large enough I'd like to be able to move instead of copying, but I can't quite figure out an elegant way to do it.

Any solutions or even just pointers (no pun intended) in a useful direction would be hugely appreciated. I also have a vague memory of reading a recipe by Stroustrup pre C++11, years ago, to move across STL containers, but there's so much C++11 stuff around these days no amount of searching served.

Thanks.


Solution

  • You couldn't move vector content in C++11 either. Move semantics would only work for the elements of the vector, but as the elements are int there is no benefit. What you want is just not possible. But if you want to avoid merging, you can store a vector of vectors:

    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
    }
    

    It all depends on what you want to do with the accumulator. If you really need to have a single vector<int>, then it may still be cheaper to merge the vectors at the end rather than appending them one by one.