对向量的元素进行排序,其中每个元素都是一对 [英] Sorting elements of vector where each element is a pair

查看:80
本文介绍了对向量的元素进行排序,其中每个元素都是一对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何根据对的第二个元素对向量进行排序?

Possible Duplicate:
How do I sort a vector of pairs based on the second element of the pair?

我有一个这种类型的向量:vector< pair<float, int> > vect;我想根据浮点值(对的第一个值)的降序对元素进行排序. 例如vect = [<8.6, 4>, <5.2, 9>, <7.1, 23>],排序后我想要的是:[<5.2, 9>, <7.1, 23>, <8.6, 4>] 我怎样才能简单地在C ++中做到这一点?

I have a vector of this type: vector< pair<float, int> > vect; I want sort its elements according to the descending order of the floats values (the first value of pairs). For example vect = [<8.6, 4>, <5.2, 9>, <7.1, 23>], after sorting I want to have: [<5.2, 9>, <7.1, 23>, <8.6, 4>] how can I simply do that in C++ ?

推荐答案

struct cmp_by_first {
  template<typename T>
  bool operator<(const T& x, const T& y) const { return x.first < y.first; }
};

std::sort(vect.begin(), vect.end(), cmp_by_first());

这篇关于对向量的元素进行排序,其中每个元素都是一对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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