Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 731
Navaneeth K N Avatar asked May 25 '09 10:05

Navaneeth K N


People also ask

Can we use any user defined data type as a key in map in C++?

We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type.

Can you use a pointer as a key to a map?

C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.

Can a string be a key in map C++?

A map is an associative container that maps keys to values, provides logarithmic complexity for inserting and finding, and constant time for erasing single elements. It is common for developers to use a map to keep track of objects by using a string key.


1 Answers

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.

like image 56
unwind Avatar answered Sep 28 '22 12:09

unwind