带有结构键的 std::map 的高效比较器

efficient comparator for an std::map with a struct key

本文关键字:map 高效 比较器 std 结构      更新时间:2023-10-16

我有一个以下类型的结构,我计划将其用作映射中的键。因此,我写了一个比较器,如下所示。我想知道是否有一种更优雅但更有效的方法。
可能正在使用std::pair什么的。

struct T 
{
  int a, b, c, d;
  bool operator< (const T& r) {
    if (a < r.a)
       return true
    else if (a == r.a)
       if (b < r.b)
          return true;
       else if (b == r.b)
            if (c < r.c) 
                return true;
            else if (c == r.c)
                if (d < r.d)
                   return true;
    return false;
  }
}

你能用C++11吗?㞖:

struct T {
    int a, b, c, d;
    bool operator<(const T& rhs) const {
        return tied() < rhs.tied();
    }
private:
    std::tuple<int, int, int, int> tied() const {
        return std::make_tuple(a, b, c, d);
    }
};

或者,我宁愿在每个可能的机会return,以避免容易出错的尴尬嵌套方法:

bool operator<(const T& rhs) const {
    if (a != rhs.a) return a < rhs.a;
    if (b != rhs.b) return b < rhs.b;
    if (c != rhs.c) return c < rhs.c;
    return d < rhs.d;
}
您可以使用

...

bool operator<(const T& r)
{
    return a < r.a ||
           a == r.a && (b < r.b || 
                        b == r.b && (c < r.c || 
                                     c == r.c && d < r.d));
}

或。。。

    return a != r.a ? a < r.a :
           b != r.b ? b < r.b :
           c != r.c ? c < r.c :
                      d < r.d;

说过您没有使用 C++11,Barry 对元组方法有一个很好的说明,但供将来参考和其他感兴趣的各方使用一些可重用的支持代码......

bool less_by_pairs()
{
    return false;
}
template <typename T, typename U, typename ...Args>
bool less_by_pairs(const T& v1, const U& v2, Args... args)
{
    return v1 != v2 ? v1 < v2 : less_by_pairs(args...);
}

。您可以更轻松地实现此类运算符...

bool operator<(const T& r)
{
    return less_by_pairs(a, r.a, b, r.b, c, r.c, d, r.d);
}

您可以做类似的事情,提供要比较的成员列表,但无论如何,它的符号实际上有点冗长。

您可以使用另一个字段来存储密钥。此键值可以通过公式生成,该公式用作输入(a,b,c,d)

这样:

void hash()
{
    key = (a ^ b ^ c ^ d);
}

因此,您只需比较此键即可知道内容是否相同。