Home >Backend Development >C++ >Why Does My Custom `std::set` Comparator Cause a Type Mismatch Error?

Why Does My Custom `std::set` Comparator Cause a Type Mismatch Error?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 14:11:17901browse

Why Does My Custom `std::set` Comparator Cause a Type Mismatch Error?

Error: Mismatched Type in Custom std::set Comparator Definition

In your code, you're attempting to specify a custom comparator function for sorting elements in a std::set using the lexicographic order instead of numeric order. However, the error message indicates that there's a type mismatch error in the declaration of your custom comparator.

The issue arises because you're declaring lex_compare as a function with two int64_t parameters that returns a boolean value. However, the template for std::set expects a comparator that implements the std::less<> template. std::less<> is a function object with the following signature:

template <typename T>
struct less {
  bool operator()(const T& a, const T& b) const;
};

To fix this issue, you need to implement lex_compare to conform to the std::less<> signature. Here's a modification to your code:

struct lex_compare {
  bool operator()(const int64_t& a, const int64_t& b) const {
    stringstream s1, s2;
    s1 << a;
    s2 << b;
    return s1.str() < s2.str();
  }
};

std::set<int64_t, lex_compare> s;

Now, the lex_compare struct implements the operator() function that takes two int64_t arguments and returns a boolean value, which matches the signature of std::less<>. By specifying this custom comparator in the definition of your std::set, you can modify the ordering behavior of the set to sort elements lexicographically.

The above is the detailed content of Why Does My Custom `std::set` Comparator Cause a Type Mismatch Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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