Search code examples
c++data-structuresstructcomparison-operators

Comparing struct in c++


Do anyone know a general method to declare a comparision function for struct so that I can use it in sort , priority queue , map ,set ...

I would also know how to specify the comparision function when declaring a data structure (like map ) having a structure as a key (in the case where i have two or more comparision functions)

Thank you in advance


Solution

  • The comparison function depends from the semantics of your struct. What does it mean that a < b for your type?

    In general, a compare function is something along the line of this (references are optional):

    bool comp( const YourType& a, const YourType& b );
    

    To make a map use your compare function, you must write like this:

    #include <map>
    
    struct YourType{
        int v;
    };
    
    struct YourTypeComparison{
        bool operator()( const YourType& a, const YourType& b ) { return a.v < b.v; }
    };
    
    int main()
    {
        std::map<YourType,int, YourTypeComparison> m;
    }