I have a vector and I would like to efficiently break out the second half of the vector into another vector using STL algorithms. Here is one way I see to do this, but expect there are more efficient and succinct answers, or at the least, one that uses the stl algorithms:
std::vector<Entry> &entries = someFunction();
int numEntries = entries.size();
// Assume numEntries is greater than or equal to 2.
std::vector<Entry> secondEntries;
std::vector<Entry>::iterator halfway = entries.begin() + numEntries / 2;
std::vector<Entry>::iterator endItr = entries.end()
// Copy the second half of the first vector in the second vector:
secondEntries.insert(secondEntries.end(), halfway, endItr);
// Remove the copied entries from the first vector:
entries.erase(halfway, endItr);
Taking a step back, keep in mind to make sure that you're working with iterators with your own algorithms, and not (necessarily) containers. So if you have this:
And now you're stuck in this situation:
Consider using iterators instead:
So now you denote ranges and not containers:
This limits the number of unnecessary containers and allocations you make.
With that out of the way, in C++11 you can do this (rest is the same):
If
Entry
has a move constructor, themove_iterator
adapter will ensure that it is used during the insertion (if it doesn't a normal copy is made). In C++03, what you have is probably best.There are several other ways of performing this task for example by using copy algorithm and an insert iterator.
But algorithmic the complexity of these actions will always be O(n) due to the nature of the vector container. Vector is not a list that allows moving big chunks of data from one container to another in a O(1) (constant) time. Depending on the particular STL implemenation one way can be 10-20% better than the other, but unlikely it will be more than that.
If data type of your container allows move semantics and you have these language features available, this will definitely help. But this is more about handling data object in the container rather than the container itself.
std::move can do a better job if you have access to a c++11 compiler and moveable objects.
Note that you still need to erase them from the first vector.