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?
For a thing to be usable as a key in a map, you have to be able to compare it using operator<()
. You need to add such an operator to your node class:
struct Node
{
int a;
int b;
bool operator<( const Node & n ) const {
return this->a < n.a; // for example
}
};
Of course, what the real operator does depends on what comparison actually means for your struct.