【问题标题】:Can I define a map whose key is a structure?我可以定义一个键是结构的映射吗?
【发布时间】:2011-04-25 12:59:41
【问题描述】:

我如何在 C++ 中做到这一点?

【问题讨论】:

    标签: c++ data-structures stl map


    【解决方案1】:

    您可以使用任何类型作为映射键,只要它实现了operator<(加上对存储在容器中的值的通常复制和分配要求)。

    例如:

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

    或者,您可以提供一个比较函数作为地图模板的第三个参数,而不是定义operator&lt;。更多详情here(参数Compare)。

    【讨论】:

    • "只要它实现了一个运算符std::less。 map默认使用lessless默认使用operator&lt;,所以里面有两条路由。
    猜你喜欢
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2012-11-04
    相关资源
    最近更新 更多