对向量的元素进行排序,其中每个元素都是一对

Sorting elements of vector where each element is a pair

本文关键字:元素 向量 排序      更新时间:2023-10-16

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

我有一个这样类型的向量: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++中简单地做到这一点?

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());
std::vector<std::pair<float, int>> vect = 
{
    std::make_pair(8.6, 4),
    std::make_pair(5.2, 9),
    std::make_pair(7.1, 23)
};
std::sort(vect.begin(), vect.end(), [](const std::pair<float, int>& first, const std::pair<float, int>& second)
{
    return first.first < second.first;
});
for (const auto& p : vect)
{
    std::cout << p.first << " " << p.second << std::endl;
}

C++11.

http://liveworkspace.org/code/5f14daa5c183f1ef4e349ea26854f1b0