Sets in C++17 and a custom comparator

Sets belong to the associative containers family. This category facilitates very fast element search. Sets contain keys that are always ordered and unique. The class template for sets is like that:

std::set<T, Comparator, Allocator>

where T is the key type, Comparator is the algorithm with which we perform the ordering and defaults to std::less and Allocator that requests dynamic memory in specific cases and defaults to std::alocator<T>

To understand easier how a set works, let’s look in the following code sample.

In this snippet, we accept a number of command-line arguments and prints them in alphanumerically sorted order. We can use std::string, as the underlying type, and everything would work like plug-and-play. However, we decided to use std::set<const char*> to store the elements, in order to create a custom comparator that compares the two C-style strings as we iterate over the set to obtain the sorted result.

In the beginning, we place the incoming command-line arguments in an std::vector using the emplace_back() method. Then, we construct the set object using the vector’s iterators by providing the half-open range.

As we said, for the C-style type, we needed to create our own custom Comparator which is a callable object like the lambda we created, the cmp. To make our life easier, we used the decltype() specifier. The comparator object is a function (invocable) with two parameters, returning true if the first argument is less than second. For our C-style strings, we employed strcmp() function to do the dirty job behind the scenes.