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

前端 未结 6 2189
离开以前
离开以前 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:15

    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.

提交回复
热议问题