Using class type as map key_value

Can a variable Databe 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
}
+3
source share
2 answers

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

An example of using a custom comparison function in the STL documentation.

+7
source

if you don't need the <operator, you can use boost :: unordered_map.

+1
source

Source: https://habr.com/ru/post/1751408/


All Articles