Home > Backend Development > C++ > How to Correctly Compile a Set with a Custom Comparator in C ?

How to Correctly Compile a Set with a Custom Comparator in C ?

Barbara Streisand
Release: 2024-12-21 00:56:10
Original
940 people have browsed it

How to Correctly Compile a Set with a Custom Comparator in C  ?

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;
Copy after login

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;
Copy after login

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);
Copy after login

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);
Copy after login

4. Struct with Operator():

struct cmp {
    bool operator() (int64_t a, int64_t b) const {
        return ...
    }
};

std::set<int64_t, cmp> s;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template