Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a class type as map key_value

Tags:

c++

stl

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
}
like image 697
cpx Avatar asked Jun 29 '26 09:06

cpx


1 Answers

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.

like image 73
James McNellis Avatar answered Jul 02 '26 00:07

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!