Search⌘ K
AI Features

Leverage Existing Algorithms: Gather

Explore how to implement the gather algorithm using C++20 STL features and the stable_partition algorithm. Understand how to move elements that meet a predicate about a pivot in containers like vectors or strings. This lesson helps you leverage existing STL algorithms to manipulate data efficiently with iterator-based techniques.

We'll cover the following...

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

Note: The even numbers are all in the middle of the output.

In this recipe, we will implement a gather algorithm using ...