Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it impossible to use an STL map together with a struct as key?

Tags:

People also ask

How do you use a struct as a key on a map?

By far the simplest is to define a global "less than" operator for your struct in stead of as a member function. std::map uses - by default - the 'lessthan' functor which, in turn, uses the global "operator<" defined for the key type of the map.

Can maps pair with keys?

Do you mean cout << mymap[make_pair(1,2)] << endl; ? (1,2) is non-sensical, at least in this context. You must have an std::pair to be used as your key, and that means following what @andre just commented. Yes!

Which data structure is used by map in STL?

List: A list in STL is used to implement the doubly-linked lists. Unlike an array, lists are used to store the data, which is not contiguous.

What is the data structure used in implementation of STL map in C++ and if you store a user define structure as key which operator must be overloaded?

A map is a data structure that stores information in the form of key and value pairs. In C++, map is defined in STL (standard template library) and store keys in an ordered form. map<key_type , value_type> map_name; The data type of any of these two data of the map can be any of the data types.


I have the following code:

struct Node
{
  int a;
  int b;
};

Node node;
node.a = 2;
node.b = 3;

map<int, int> aa;
aa[1]=1; // OK.

map<Node, int> bb;
bb[node]=1; // Compile error.

When I tried to map an instance of my struct Node to an int, I got a compile error. Why?