Can I define a map whose key is a structure?

后端 未结 1 1805
执念已碎
执念已碎 2021-02-19 07:35

and how can I do it in C++?

1条回答
  •  心在旅途
    2021-02-19 08:25

    You can use any type as a map key, as long as it implements an operator< (plus the usual copy-and-assign requirements for values stored in containers).

    For instance:

    struct example { int x; }
    
    bool operator < (const example &l, const example &r) { return l.x < r.x; }
    
    std::map values;
    

    Alternatively, you may provide a comparison function as the third argument of the map template instead of defining operator<. More details here (parameter Compare).

    0 讨论(0)
提交回复
热议问题