3

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

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++ ?

Community
  • 1
  • 1
shn
  • 5,116
  • 9
  • 34
  • 62
  • 1
    function, that take the first element in pair and compare it. is it possible for you? (after this you can make any realization of sorting function or use libraries like `boost`) – gaussblurinc Jul 26 '12 at 09:08
  • check this one out. it's a boost solution -> http://stackoverflow.com/questions/279854/how-do-i-sort-a-vector-of-pairs-based-on-the-second-element-of-the-pair – Emir Akaydın Jul 26 '12 at 09:09

2 Answers2

4
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());
pmr
  • 58,701
  • 10
  • 113
  • 156
4
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

ForEveR
  • 55,233
  • 2
  • 119
  • 133