Sign in with Google to keep private notes

STL::Algorithm implementation in C++

Containers, Algorithms, Iterators.

Please Let Me Into Virtu Financial.

(To get in I want to have access to some algorithms that can reduce boiletplate and dumb bugs)

Link to all algorithms: https://en.cppreference.com/cpp/algorithm

Why use iterators (begin(table)) instead of indexing (table[i])?

// Iterator-based approach (from lecture)
auto smallest = begin(table);

for (auto pos = begin(table) + 1; pos != end(table); ++pos) {
    if (pos->age < smallest->age) {
        smallest = pos;
    }
}

The main benefit is generality. Indexing works well for std::vector, but not all STL containers support it (e.g., std::list and std::set). Iterators provide a common interface for traversing different containers, allowing STL algorithms like std::min_element() to work across them. For std::vector, both approaches are efficient, so iterators offer no inherent performance advantage.

To get the min element, I can use the min_element. It should give me back an iterator. The iterator can be used to. Also min_element would require a lambda to understand how to compare, for example classes. There's a unique overload for it. std::min_element(start_it, end_it, comp)

//under the hood, if the callable passed in returns true
// then that becomes a new minimum elemene
for (; first != last; ++first) {
    if (comp(*first, *smallest)) {
        smallest = first;
    }
}

This is callled the

Strategy Design Pattern

auto const pos = std::min_element( begin(table), end(table) ),
    []( Person const& lhs, Person const& rhs )
    {
        return lhs.age < rhs.age;
    }

And if you want to get even more insane, you can make use of the ranges algorithm

(Small note: forwarding references get involved pretty soon after this)

min_element ( I first, S last, Comp comp = {}, Proj proj = {} );
//alternatively, you can use a "whole range" form
min_element ( R&& r, Comp comp = {}, Proj proj = {} );

Yeah the projector can do some casting to make the two templates comparable. In my lambda C++ notes I noted this use case for comparing lower case words. And the same idea comes back here. Yay.

and we can use it like this

Now, we can pass in an instance of the std::ranges::less{} comparator

(side note its an empty struct so you can only initialise an instance with the curly braces)

So the way this would probably play out is

std::ranges::min_element ( table, std::less{}, &Person::age );
// :D. Oh wait because std::less{} is the default argument
std::ranges::min_element ( table, {}, &Person::age );

Rapid fire:

  1. std::partition(first, last, comp) to sort an array into 2 distinct parts
  2. std::iter_swap to do a convenient swap
  3. std::rotate (or std::ranges::rotate)
// From slide 54
std::rotate(begin(table), pos, end(table));
// Example:
// Before: [A, B, C, D, E]
//              pos -> C
// After:  [C, D, E, A, B]
  1. accumulate
std::accumulate( begin(table), end(table), 0,   
[] (int val, Person const& p){
    return val + p.age;
})

which is better only because it avoids the Initialise Then Modify anti-pattern

  1. reduce (the multithreaded version of the above)

You can get access to execution policies.

Namely: seq, par, par_unseq and unseq.

par -> parallel -> thread parallel

par_unseq -> parallel and SIMD

unseq -> parallelise by SIMD and still seq

template< class ExecutionPolicy, class ForwardIt > 
typename std::iterator_traits<ForwardIt>::value_type
    reduce ( ExecutionPolicy&& policy,
             ForwardIt first, ForwardItlast );


Now all you need to do is

auto const sum = std::reduce ( std::execution::par, 
                std::begin(values), std::end(values), double{} );

So it works out of the box.

for more algos:

https://www.youtube.com/watch?v=2olsGf6JIkU&vl=en

(105 STL algorithms in less than an hour)

https://www.youtube.com/watch?v=W2tWOdzgXHA

(C++ seasoning)

https://www.youtube.com/watch?v=pUEnO6SvAMo

(Connor Hockstra)

Generally speaking just try to use algorithms as much as possible. Try to cut out the number of for loops, and the only time you do try to keep their bodies short.

Articles to read next