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

前端 未结 6 2193
离开以前
离开以前 2020-12-14 03:46

I have the following code:

struct Node
{
  int a;
  int b;
};

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

map aa;
aa[1]=1; // OK.

map

        
6条回答
  •  一生所求
    2020-12-14 04:02

    You have to tell std::map how to compare the Node objects. By default it tries to do so by using the less than operator. But you didn't provide any less than operator for Node. The easiest solution would be to supply one.

    Free function example:

    bool operator<(Node const& n1, Node const& n2)
    {
        return n1.a

    Note that, for any pair of node objects x,y with !(x and !(y the map will regard x and y as equal (same key).

提交回复
热议问题