How can I use a custom type as key for a map in C++?

23,582

Solution 1

I suspect you need

bool operator<(const Foo& foo1) const;

Note the const after the arguments, this is to make "your" (the left-hand side in the comparison) object constant.

The reason only a single operator is needed is that it is enough to implement the required ordering. To answer the abstract question "does a have to come before b?" it is enough to know whether a is less than b.

Solution 2

It's probably looking for const member operators (whatever the correct name is). This works (note const):

bool operator<(const Foo& foo1) const { return foo_value < foo1.foo_value;}

EDIT: deleted operator> from my answer as it was not needed (copy/paste from question) but it was attracting comments :)

Note: I'm 100% sure that you need that const because I compiled the example.

Share:
23,582

Related videos on Youtube

Navaneeth K N
Author by

Navaneeth K N

Nothing serious about me.

Updated on August 04, 2020

Comments

  • Navaneeth K N
    Navaneeth K N almost 4 years

    I am trying to assign a custom type as a key for std::map. Here is the type which I am using as key:

    struct Foo
    {
        Foo(std::string s) : foo_value(s){}
    
        bool operator<(const Foo& foo1) {   return foo_value < foo1.foo_value;  }
    
        bool operator>(const Foo& foo1) {   return foo_value > foo1.foo_value;  }
        
        std::string foo_value;
    };
    

    When used with std::map, I am getting the following error:

    error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:\program files\microsoft visual studio 8\vc\include\functional 143
    

    If I change the struct to the one below, everything works:

    struct Foo
    {
        Foo(std::string s) : foo_value(s)   {}
    
        friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value;  }
    
        friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value;  }
        
        std::string foo_value;
    };
    

    Nothing changed, except that the operator is overloaded as friend. Why does my first code not work?

  • Nubzor
    Nubzor almost 15 years
    Funny stackoverflow shows previous answer 10 minutes ago but when I submit my answer there wasn't any yet ... hence the same answer
  • bobobobo
    bobobobo over 14 years
    Can you go into more detail? Why do you only need operator< and not operator== or operator>?
  • skrebbel
    skrebbel over 13 years
    because you can derive operator> and operator== from operator<. (b < a) implies (a > b), so there's operator>. and, (!(a < b) && !(b < a)) means that a isn't less than b nor greater than b, so it must be equal to b.
  • siddhusingh
    siddhusingh over 10 years
    Since object is constant const function would be required.