Leverage existing algorithms: gather
gather()
is an example of an algorithm that leverages existing algorithms.
The gather()
algorithm takes a pair of container iterators and moves the elements that satisfy a predicate toward a pivot position within the sequence, returning a pair
of iterators that contains the elements that satisfy the predicate.
For example, we could use a gather
algorithm to sort all the even numbers to the mid-point of a vector
:
vector<int> vint{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; gather(vint.begin(), vint.end(), mid(vint), is_even); for(const auto& el : vint) cout << el;
Our output is:
1302468579
Notice that the even numbers are all in the middle of the output.
In this recipe, we will implement a gather
algorithm using standard STL algorithms.
How to do it…
Our gather
algorithm uses the std::stable_partition()
algorithm to move items before the pivot iterator and again to move items past the pivot.
- We put the...