带有结构键的 std::map 的高效比较器
efficient comparator for an std::map with a struct key
我有一个以下类型的结构,我计划将其用作映射中的键。因此,我写了一个比较器,如下所示。我想知道是否有一种更优雅但更有效的方法。
可能正在使用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);
}
因此,您只需比较此键即可知道内容是否相同。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- C++中高效的大型稀疏块压缩线性方程
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 如何在C++中高效地构造随机骰子
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 使用字符数组作为 Map 中的键
- 带有结构键的 std::map 的高效比较器
- std::map的高效线程同步技术
- 如何在c++中高效地创建map中的map