The STL algorithms library that provides unified functions for sorting, counting, manipulation, as well a many other things. It works with ranges which are defined as beginning to end where end is non-inclusive.
C++20 has added constrained algorithms. In these algorithms, a range can be specified as an iterator pair or a single range. For example:
std::vector<int> data {5, 4, 2, 3, 1};
std::ranges::sort(v);
To use algorithms, we include the algorithm header.
std::all_of checks a collection to see if all of the elements match a predicate. Std::any_of does the same but returns true if any of the elements match and std::none_of returns true if none of the elements match. The callback can be a lambda, a functor, or a function pointer. For example:
int data[] {1, 2, 3, 4, 5};
if (std::all_of(std::begin(data), std::end(data), [](int i) { return i % 2 == 0; })) {
std::for_each applies an operation to each element in the container. The callback can be a lambda, a functor, or a function pointer. For example:
int data[] {1, 2, 3, 4, 5};
std::for_each(std::begin(data), std::end(data), [](int &i) { i *= i; });
std::max_element finds the largest element in the range and std::min_element finds the smallest. Std::minmax_element finds both as a pair of forward iterators. They return an iterator to the element found. There are overloads with and without a callback. If we use the callback, all the types are supported. For example:
int data[] = {1, 2, 3, 4, 5};
auto result = std::max_element(std::begin(data), std::end(data));
std::find finds and returns an iterator to an element matching the value passed. Std::find_if does the same but takes an additional predicate.
std::copy copies elements from one collection to another. It takes three iterators Where to start copying, where to stop copying, and where to copy to. There is also a copy_if version that takes an additional predicate. For example:
std::vector<int> from {1, 2, 3, 4, 5}
std::vector<int> to {10, 11, 12, 13, 14, 15};
std::copy(from.begin(), from.begin()+4, to.begin(); // Overwrites the first four elements in to
std::sort sorts a collection. It requires that the collection implements RandomIterator. so collections like list can’t be sorted. It can take a predicate to handle how the sorting is done. It sorts in place.
There are ranges based versions of the algorithms which live in the std::ranges namespace and take a collection directly.
Read more about algorithms.