Search code examples
c++comparatorstd

Inbuilt / pre-defined comparator in cpp


Recently I learnt about comparators in cpp from STL.

I came to know we can use greater<>() as third argument for sorting instead of writing own logic.

Just curious to know how many inbuilt comparators are there in cpp.


Solution

  • The standard library defines pretty much what you would expect as analogues to the built-in operators:

    std::equal_to      // ==
    std::not_equal_to  // !=
    std::less          // <
    std::less_equal    // <=
    std::greater       // >
    std::greater_equal // >=
    

    Since C++20 also constrained versions of all these comparison function objects in the std::ranges namespace as well as std::compare_­three_­way, which is the analogue to the built-in three-way comparison operator <=>.

    For a reference of these function objects see https://en.cppreference.com/w/cpp/utility/functional#Comparisons.