自定义排序向量的元组 [英] Custom Sorting a vector of tuples

查看:73
本文介绍了自定义排序向量的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组向量

vector<tuple<T1, T2, T3>> v;

我相信,当元组类型的默认比较开始时,它将执行字典比较。

I believe that when the default comparison kicks in for tuple types, it performs a lexicographical comparison.

我可以通过选择的元素执行比较吗?例如,通过上面示例中的第二个元素或包含m个类型的元组中的第ith个元素

Can I perform the comparisons by the element I choose ? Eg by the second element in the above example or by the ith element in a tuple containing m types ?

谢谢。

推荐答案

有很多方法可以做到这一点,我使用的方法可以归结为声明一个自定义比较对象,实际上,以下是

There are many ways to do that, the one I use boils down to declaring a custom comparison object, actually the following

// Functor to compare by the Mth element
template<int M, template<typename> class F = std::less>
struct TupleCompare
{
    template<typename T>
    bool operator()(T const &t1, T const &t2)
    {
        return F<typename tuple_element<M, T>::type>()(std::get<M>(t1), std::get<M>(t2));
    }
};

适用于任意长度的元组 (避免使用可变参数模板-尽管以可变的方式进行操作相当简单和安全,因为您可以将operator()的参数声明为任意长度的元组),并且可用于对您可以向其传递自定义比较功能/对象,但将< 运算符用作默认策略。用法示例为

It works for tuples of arbitrary length (avoiding variadic templates - even though it's fairly easy and safer to do it the variadic way because you can declare the arguments of operator() as tuples of arbitrary length) and also works for pairs and you can pass it a custom comparison function/object but uses < operator as the default policy. An example usage would be

int main()
{
    vector<tuple<int, string>> v;
    v.push_back(make_tuple(1, "Hello"));
    v.push_back(make_tuple(2, "Aha"));

    std::sort(begin(v), end(v), TupleCompare<0>());
    return 0;
}

当然,还有一种更现代的方式,就是使用lambda,因此排序行将是

there is ofcourse a more modern way, by using lambdas, so the sorting line would be

std::sort(begin(v), end(v), 
    [](tuple<int, string> const &t1, tuple<int, string> const &t2) {
        return get<0>(t1) < get<0>(t2); // or use a custom compare function
    }
);

我认为值得为此创建一个函数对象(避免大量样板代码),并且第一种方法

I believe it's worth making a function object for this (avoids a lot of boilerplate code) and go with the first approach

如Yakk的评论(在c ++ 1y)成为标准兼容(c ++ 14),我们在下面展示通用lambda

As Yakk's comment (on c++1y) became standard compliant (c++14), we demonstrate below the case for generic lambdas

std::sort(begin(v), end(v), [](auto const &t1, auto const &t2) {
        return get<0>(t1) < get<0>(t2); // or use a custom compare function
});

TupleCompare 的机制非常匹配 operator()也是模板。

which greatly matches the mechanics of TupleCompare since the operator() is templated as well.

这篇关于自定义排序向量的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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