Sorting and comparing std::optional

The std::optional is both equally comparable and sortable, using the following rules as shown in the following table:

Two empty optional's are considered equal.

auto a = std::optional<int>{};auto b = std::optional<int>{};auto c = std::optional<int>{4};assert(a == b);assert(b != c);

An empty optional is considered less than a non-empty.

auto a = std::optional<int>{};auto b = std::optional<int>{4};auto c = std::optional<int>{5};assert(a < b);assert(b < c);

Therefore, if you sort a container of std::optional<T>, the empty optional's would end up at the beginning of the container, whereas the non-empty optional's are sorted as usual, shown as follows:

auto c = std::vector<std::optional<int>>{{3}, ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.