I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can\'t get the following to compile with g++:
auto cmp = [](int a, int b) { return ... };
std::set s;
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
Online demo
auto cmp = [](int a, int b) { return ... };
std::set s(cmp);
Before C++20 we need to pass lambda as argument to set constructor
Online demo
Make comparator as usual boolean function
bool cmp(int a, int b) {
return ...;
}
Then use it, either this way:
std::set s(cmp);
Online demo
or this way:
std::set s(&cmp);
Online demo
()
operatorstruct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set s;
Online demo
Take boolean function
bool cmp(int a, int b) {
return ...;
}
And make struct from it using std::integral_constant
#include
using Cmp = std::integral_constant;
Finally, use the struct as comparator
std::set set;
Online demo