【问题标题】:Sorting elements of vector where each element is a pair [duplicate]对向量的元素进行排序,其中每个元素都是一对[重复]
【发布时间】:2012-07-26 09:06:41
【问题描述】:

可能重复:
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++ 中简单地做到这一点?

【问题讨论】:

  • 函数,它取第一个元素并进行比较。你有可能吗? (之后可以任意实现排序功能或使用boost等库)
  • 看看这个。这是一个提升解决方案 -> stackoverflow.com/questions/279854/…

标签: c++ sorting vector


【解决方案1】:
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());

【讨论】:

    【解决方案2】:
    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

    【讨论】:

    • 既然是 c++11,你可以说:std::vector > vect = {{8.6, 4}, {5.2, 9}, { 7.1, 23}};
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-02-12
    • 1970-01-01
    • 2021-07-12
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多