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

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

    If you don't really need to have your data sorted by key, you can use the new unordered_map:

    #include 
    
    ... 
    
    std::tr1::unordered_map aa;  // Doesn't require operator<(Node, Node)
    

    You'll need a recent compiler for this to work.

    UPDATE As Neil points out you need an specialized hash function if you want an unordered_map with Node keys.

    struct NodeHash : std::unary_function
    { 
        size_t operator()(Node const & node) const
        {
            return static_cast(node.a + 1) * static_cast(node.b + 1);
        }
    };
    

    And then the map becomes:

     std::tr1::unordered_map aa;
    

    Also, as sellibitze says, an operator== is needed to compare keys in case of hash collision:

    bool operator==(const Node & lhs, const Node & rhs)
    {
        return lhs.a == rhs.a && rhs.b == rhs.b;
    }
    

    So I guess that std::map is much easier to use after all.

提交回复
热议问题