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
  • 90,891
  • 40
  • 158
  • 247
user977154
  • 975
  • 4
  • 17
  • 38

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
  • 216,937
  • 30
  • 383
  • 461
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
  • 90,891
  • 40
  • 158
  • 247
0

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

Vadiklk
  • 3,564
  • 4
  • 27
  • 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
  • 41,374
  • 10
  • 77
  • 101