What is the C++ nth_element algorithm?

The C++ standard library provides an algorithm called nth_element() that is a useful tool for partial sorting. But how does it work and where is it useful? First of all, the algorithm is defined as follows: given a range [first, last) and an nth element within the range, the algorithm partially sorts the range so…

Understanding equal_range

std::equal_range is a general purpose standard algorithm used to find a sub-range of values in a given sorted or at least partitioned range. In this post, I will explain how the algorithm works.

Transform and reduce alternatives

Transform-reduce is a pattern in which a set of data is first modified by applying a transformation on each of the elements and then it is reduced to a single value. In C++, this can be implemented straightforwardly with std::transform and std::accumulate. In C++17, an alternative for std::accumulate is available; std::reduce sums a range of elements just like std::accumulate, except that it does so out of order. That means you cannot use it with operators that are not communicative or associative (including overloads of operator+ that don’t exhibit these properties). On the other hand, there is yet another algorithm called std::transform_reduce that applies a functor to all the elements of a range and then reduces them, all in an out of order manner. And then, there are also parallel versions of these algorithms. In this post, I will try to compare the performance of these possible alternatives for implementing transform-reduce.