1

I am trying to sort a 2D vector with the type:

vector<pair<char, double>> output;

I am trying to arrange them from the highest to lowest double value and only displaying the top 5. This is what I am trying to do:

sort(output.begin(), output.end());

But this sort is not working properly for me. What am I doing wrong?

David G
  • 94,763
  • 41
  • 167
  • 253
user977154
  • 1,045
  • 4
  • 19
  • 39

4 Answers4

3

By default, std::sort will use the less-than comparison operator for the elements of the container, which will perform am lexicographical comparison using the char first and then the double.

You can use your own ordering function/functor that orders based on the pair's double element only:

bool cmp(const std::pair<char, double>& lhs, 
         const std::pair<char, double>& rhs)
{
  return lhs.second > rhs.second;
}

then

std::vector<std::pair<char, double>> output = ....;
sort(output.begin(), output.end(), cmp);

See working demo here.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

As Violet said, you may want to include your own comparison function:

class compare
{
public:
    bool operator() (std::pair<char, int> const& p1,
                    std::pair<char, int> const& p2) const
    {
        // perform logic here
    }
} Predicate;

std::sort uses operator < to compare the elements, and sorts them accordingly. It has an extra optional parameter for the comparsion functor, which we can include like this:

std::sort(output.begin(), output.end(), Predicate);

Note that this can also be done using a lambda in C++11.

David G
  • 94,763
  • 41
  • 167
  • 253
  • I'm not sure, but the comparator has not to be a thing (function, lambda, functor) with signature `bool(const value_type& , const value_type&)`? I think you should write `operator()` instead of `operator<` – Manu343726 Oct 08 '13 at 19:50
  • @Manu343726 That is exactly what this is. `std::sort` will call `compare::operator <` internally. – David G Oct 08 '13 at 19:52
  • mmmm no, is not a callable object, you have defined comparison operator only. – Manu343726 Oct 08 '13 at 19:53
0

You need to write a comparison operator between the pair<char, double> operands. http://en.cppreference.com/w/cpp/algorithm/sort

Vadiklk
  • 3,696
  • 5
  • 28
  • 44
0

Is there a reason you're using a vector of pairs? In other words, does the order in which the elements are stored internally really matter to you? If not, you're probably better off using a map<double,char> with a reverse iterator to get the last 5 elements sorted by double value.

Carl
  • 43,122
  • 10
  • 80
  • 104