You need to define less-than operator to enable comparisons for your Node type:
struct Node
{
int a;
int b;
};
bool operator<(Node const& n1, Node const& n2)
{
// TODO: Specify condition as you need
return ... ;
}
Here you may check what LessThan Comparable mean for a user-defined type.
Alternative solution is to define a functor based on std::binary_function. From design point of view, this option has advantages because comparison is effectively decoupled from the Node
class. This makes it possible to define maps specialised with different comparison conditions (functors).
#include <map>
struct Node
{
int a;
int b;
};
struct NodeLessThan
: public std::binary_function<Node, Node, bool>
{
bool operator() (Node const& n1, Node const& n2) const
{
// TODO: your condition
return n1.a < n2.a;
}
};
int main()
{
Node node;
node.a = 2;
node.b = 3;
typedef std::map<Node, int, NodeLessThan> node_map_t;
node_map_t bb;
bb[node] = 1;
}
So, you can define more comparisons than just NodeLessThan
, for example using different conditions or one comparing only by Node::a
another comparing both components, Node::a
and Node::b
. Then, defined different types of maps:
typedef std::map<Node, int, NodeLessThan> node_map_t;
typedef std::map<Node, int, NodeLessThanByA> node_map_a_t;
Such decoupling is less intrusive (does not touch Node class at all) and is beneficial to achieve more extensible solution.