Ch8.6: Typical Algorithms
Overview
The ranges library provides many algorithms for everyday tasks: searching, counting, transforming, and removing elements. This chapter introduces the ones you will use most often.
You will learn:
- how to find elements
- how to count elements
- how to transform elements
- how to remove elements
- how projections interact with these algorithms
1. Finding elements
std::ranges::find searches for a specific value.
::fast_io::vector<int> v{3, 1, 4, 1, 5};
auto it = ::std::ranges::find(v, 4);
if (it != v.end()) {
print("found: ", *it, "\n");
}
If the value is not found, the iterator equals v.end().
2. Finding with a condition
find_if searches using a predicate:
auto it = ::std::ranges::find_if(v, [](int x) {
return x % 2 == 0; // find first even number
});
The predicate receives each element and returns true for a match.
3. Counting elements
count counts exact matches:
auto c = ::std::ranges::count(v, 1);
print("count of 1 = ", c, "\n");
count_if counts by condition:
auto evens = ::std::ranges::count_if(v, [](int x) {
return x % 2 == 0;
});
4. Transforming elements
transform applies a function to each element and writes the
result to an output range.
::fast_io::vector<int> out(v.size());
::std::ranges::transform(v, out.begin(), [](int x) {
return x * 2;
});
The input is unchanged; the output contains the transformed values.
5. Removing elements
remove and remove_if do not erase elements.
They move the “kept” elements to the front and return an iterator to the
new logical end.
auto new_end = ::std::ranges::remove(v, 1).begin();
To actually erase elements, call erase on the container:
v.erase(new_end, v.end());
This pattern is known as the “erase–remove idiom.”
6. Using projections with typical algorithms
Many algorithms accept a projection. Suppose we have:
struct Item {
int key;
int value;
};
::fast_io::vector<Item> items{
{3, 100},
{1, 200},
{2, 300}
};
We can count how many items have an even key:
auto c = ::std::ranges::count_if(items, [](Item const& x) {
return x.key % 2 == 0;
});
Or use a projection directly:
auto c = ::std::ranges::count_if(items, [](int k) {
return k % 2 == 0;
}, &Item::key);
The projection &Item::key extracts the key member
before the predicate sees it.
7. Where to learn more
This chapter introduced the most commonly used algorithms. The C++ standard library contains many more, and you can browse the complete list at:
Key takeaways
findandfind_ifsearch for elements.countandcount_ifcount elements.transformapplies a function to each element.removeandremove_ifrequire the erase–remove idiom.- Many algorithms accept projections, including
&Item::key. - cppreference provides the full list of algorithms.