【问题标题】:std::map with key as a struct with three int members [duplicate]带有键的 std::map 作为具有三个 int 成员的结构 [重复]
【发布时间】:2021-06-29 06:15:31
【问题描述】:

我想使用具有三个整数成员的结构作为键。如何重载

bool operator < (const CacheKey& a, const CacheKey& b) {
    return a.x < b.x || (a.x == b.x && a.y < b.y);
}

【问题讨论】:

  • 是什么阻止了你为三个成员做同样的事情?你只需要一个明确的顺序,它可以防止重复。
  • 只有三者相等时才需要比较相等。
  • 从成员中创建一个元组,然后进行比较

标签: c++ stl


【解决方案1】:

通用解决方案是:

if (a.x != b.x) return a.x < b.x;
if (a.y != b.y) return a.y < b.y;
// ...
return false;

或者:

return std::tie(a.x, a.y) < std::tie(b.x, b.y);

(在这种情况下,您可能希望创建一个返回绑定成员的成员函数,以便能够为所有需要的运算符执行类似a.tie() &lt; b.tie() 的操作。)

或者,在 C++20 中,您可以在类中添加以下内容以自动获取所有比较运算符,包括 &lt;

auto operator<=>(const CacheKey &) const = default;

【讨论】:

    【解决方案2】:

    最直接的方法是:

    class Foo {
        friend bool operator<(const Foo&, const Foo&);
        int a, b, c;
    }
    
    bool operator<(const Foo& lhs, const Foo& rhs) {
        return (lhs.a < rhs.a) || 
                (lhs.a == rhs.a && lhs.b < rhs.b) ||
                (lhs.a == rhs.a && lhs.b == rhs.b && lhs.c < rhs.c);
    }
    

    【讨论】:

    • 我的错误 rawrex,这是一个错字。谢谢,你的回答有效。
    • @samofoz 太棒了!祝你好运!
    • 这种方法的缺点是它需要 n 个成员的 O(n^2) 代码。
    • @HolyBlackCat 真的!因为是最直接的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多