如何在C ++中有效地排序四重结构? [英] How do I sort efficiently a quadruple structs in C++?

查看:135
本文介绍了如何在C ++中有效地排序四重结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构与成员x,y,z和w。如何有效地排序
先由x,然后由y,由z,最后由C在C ++?

I have a struct with members x,y,z and w. How do I sort efficiently first by x, then by y, by z and finally by w in C++?

推荐答案

如果要实现词典顺序,则最简单的方法是使用 std :: tie 来实现小于或大于比较运算符或函子,以及然后使用 std :: sort

If you want to implement a lexicographical ordering, then the simplest way is to use std::tie to implement a less-than or greater-than comparison operator or functor, and then use std::sort on a collection of your structs.

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 ,可能更好的是定义比较函子而不是实现比较运算符。然后你可以传递这些来排序:

If there is not a natural ordering for Foo, it might be better to define comparison functors instead of implementing comparison operators. You can then pass these to sort:

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 tuple_users_guide.htmlrel =nofollow> boost.tuple库

If you do not have C++11 tuple support, you can implement this using std::tr1::tie (use header <tr1/tuple>) or using boost::tie from the boost.tuple library.

这篇关于如何在C ++中有效地排序四重结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆