Compiling Set with Custom Comparator
When attempting to create a set of integers ordered by lexicographic comparison instead of numeric, issues can arise when compiling with g .
The error encountered is due to an incorrect template parameter type for the set. In the provided code:
set<int64_t, lex_compare> s;
lex_compare is not a type but a function. To fix this, we need to create a comparator object as per C 's template requirements.
Modern C Solutions
1. C 20 Solution:
auto cmp = [](int64_t a, int64_t b) { return ... }; std::set<int64_t, decltype(cmp)> s;
Lambdas can be used as comparators in C 20. The lambda should return a boolean value indicating the order of the elements.
2. C 11 Solution:
auto cmp = [](int64_t a, int64_t b) { return ... }; std::set<int64_t, decltype(cmp)> s(cmp);
In C 11, lambdas must be passed as an argument to the set constructor.
Traditional Solutions
3. Function Pointer:
bool cmp(int64_t a, int64_t b) { return ...; } std::set<int64_t, decltype(cmp)*> s(cmp);
4. Struct with Operator():
struct cmp { bool operator() (int64_t a, int64_t b) const { return ... } }; std::set<int64_t, cmp> s;
5. Struct from Boolean Function:
bool cmp(int64_t a, int64_t b) { return ...; } #include <type_traits> using Cmp = std::integral_constant<decltype(&cmp), &cmp>; std::set<int64_t, Cmp> set;
The above is the detailed content of How to Correctly Compile a Set with a Custom Comparator in C ?. For more information, please follow other related articles on the PHP Chinese website!