Post

C++ std -- functional

Various components inside header <functional>.

std::less and std::greater

These are two structs with trivial implementation of operator(). It relies on the value type to implement operator< or be a primitive type such as int.

Let’s how std containers implement operator<. Before that, let’s quickly take a look at std::lexicographical_compare. The implementation basically says that it compares two containers from left to right until it finds a[i] < b[i] or a is shorter than b.

First, let’s check std::array. The definition is here. It basically calls std::lexicographical_compare. However, we need to be cautious that this comparator is defined only for the same array type. The signature is operator<(const array<_Tp, _Size>& __x, const array<_Tp, _Size>& __y) not operator<(const array<_Tp, _Size>& __x, const array<_Tp2, _Size2>& __y). Both the type and size should be the same, otherwise, you will see a compilation error.

Second, let’s check std::vector. The definition is here. Similar to std::array. The two vectors should have the same type. However, it allows to have different size. Namely std::vector<int>{1, 2} < std::vector<int>{1, 2, 1}.

Third, std::pair. OK. it has its own implementation, but still trivial enough.

Forth, std::tuple. It uses a SFINAE trick implementation.

This post is licensed under CC BY 4.0 by the author.