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
Entryhas a move constructor, themove_iteratoradapter 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.