tags:

views:

58

answers:

2

Could a variable of Data be used as a map key?

struct Data {
Data(int X, int Y) {x=X; y=Y;}
int x; int y;
}

int main()
{
   std::map<Data, int> map_;
   map_.insert(std::make_pair(Data(1,2), 0)); //error inserting
}
+7  A: 

Yes, but you either need to define operator< for the class type or use a custom comparison function for the std::map.

There is an example of using a custom comparison function in the STL documentation.

James McNellis
+1 for suggesting the comparison functor, too many times it does not make sense to define `operator<`.
Matthieu M.
+1 from me as well for same reason. It might also be useful to point out that std::pair already provides this.
+1  A: 

if you don't want an operator<, you can use boost::unordered_map.

Alexandre C.