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

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

    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 
    
    struct Node
    {
     int a;
     int b;
    };
    
    struct NodeLessThan
        : public std::binary_function
    {
        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_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_map_t;
    typedef std::map node_map_a_t;
    

    Such decoupling is less intrusive (does not touch Node class at all) and is beneficial to achieve more extensible solution.

提交回复
热议问题