c++ - 如何在 C++ 中有效地对四重结构进行排序?

标签 c++ c++11 stl tuples lexicographic

我有一个包含成员 x、y、z 和 w 的结构。如何高效排序 在 C++ 中先按 x,然后按 y,按 z,最后按 w?

最佳答案

如果你想实现字典排序,那么最简单的方法就是使用std::tie。实现小于或大于比较运算符或仿函数,然后使用 std::sort 在你的结构集合上。

struct Foo
{
  T x, y, z, w;
};

....    
#include <tuple> // for std::tie

bool operator<(const Foo& lhs, const Foo& rhs)
{
  // assumes there is a bool operator< for T
  return std::tie(lhs.x, lhs.y, lhs.z, lhs.w) < std::tie(rhs.x, rhs.y, rhs.z, rhs.w);
}

....

#include <algorithm> // for std::sort

std::vector<Foo> v = ....;
std::sort(v.begin(), v.end());

如果 Foo 没有自然顺序, 最好定义比较仿函数而不是实现比较运算符。然后您可以将这些传递给排序:

bool cmp_1(const Foo& lhs, const Foo& rhs)
{
  return std::tie(lhs.x, lhs.y, lhs.z, lhs.w) < std::tie(rhs.x, rhs.y, rhs.z, rhs.w);
}

std::sort(v.begin(), v.end(), cmp_1);

如果您没有 C++11 tuple支持,您可以使用 std::tr1::tie 来实现它(使用标题 <tr1/tuple> )或使用 boost::tie来自 boost.tuple library .

关于c++ - 如何在 C++ 中有效地对四重结构进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17080729/

相关文章:

C++理解问题——链表和栈

c++ - 为什么 Visual Studio 不允许我在 enable_if 中使用模板化的 constexpr 函数?

c++ - 在 Qt 中正确使用 C++11 基于范围的 for 循环

c++ - 存储指向 map 中包含的对象的指针

c++ - std::map - 如何更改键排序?

C++ 需要从数组中删除某些值

c++ - LNK2019:未解析的外部符号;我健忘了吗?

c++ - openssl 椭圆曲线

c++ - (g++ 4.7.1) 用等效类 typedef 替换显式类型名称无法编译

C++ STL 列表大小