Add vector to another with move (pre C ++ 11)

I process some relatively large ints vectors, and I have one top-level vector that I need to copy the results of other (temporary) vectors into.

Expanding it in place, unfortunately, is not an option, since I get temporary vectors pre-prepared from another API, and I am stuck with GCC 4.1.2 for the same reason, so none of the sympathetic semantic movements or std :: move C ++ 11.

I am currently copying with an insert, something like:

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

Since temp is usually one-time, and the data can be quite large, I would like to be able to move rather than copy, but I cannot figure out an elegant way to do this.

Any decisions or even just pointers (not intended for puns) in the useful direction would be greatly appreciated. I also have a vague recollection of how Struustrup pre C ++ 11 years ago redesigned the STL recipe to navigate STL containers, but these days there was nothing in C ++ 11.

Thanks.

+7
c ++ stdvector move
source share
2 answers

You could not move vector content to C ++ 11. Moving semantics will only work for vector elements, but since there are int elements, there is no benefit. What you want is simply impossible. But if you want to avoid merging, you can save the 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 battery. If you really need to have one vector<int> , then it can still be cheaper to combine the vectors at the end rather than adding them one by one.

+3
source share

The only way to avoid copying data (and redistributing), in particular without C ++ 11, is to accumulate in 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)); } 
+2
source share

All Articles