如何基于对的第二个元素对对的向量排序? [英] How do I sort a vector of pairs based on the second element of the pair?

查看:161
本文介绍了如何基于对的第二个元素对对的向量排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一对向量:

std::vector<std::pair<int, int> > vec;

有没有简单的方法根据对的第二个元素以递增的顺序排序列表?

Is there and easy way to sort the list in increasing order based on the second element of the pair?

我知道我可以写一个小函数对象来完成这项工作,但是有一种方法可以使用 STL std :: less 可以直接进行工作?

I know I can write a little function object that will do the work, but is there a way to use existing parts of the STL and std::less to do the work directly?

编辑:我明白我可以写一个单独的函数类传递给第三个参数进行排序。问题是我是否可以从标准的东西。我真的会看起来像这样:

I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:

std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());


推荐答案



You can use boost like this:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

我不知道一个标准的方法做同样简短和简洁,但你可以抓住 boost :: bind 它都包含头文件。

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.

这篇关于如何基于对的第二个元素对对的向量排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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