c++ custom compare function for std::sort()

28

I want to create custom compare function for std::sort(), to sort some key-value pairs std::pair

Here is my function

 template <typename K, typename V>
 int comparePairs(const void* left, const void* right){
        if((((pair<K,V>*)left)->first) <= (((pair<K,V>*)right)->first))
            return 1;
        else 
            return -1;
    }

Then, inside some class I have vector of pairs class member:

vector<pair<K,V>> items;  

And some method for sort this vector by keys, using std::sort()

std::sort(items.begin(), items.end(), comparePairs<K,V>);

I have compilation errors within , which said

"cannot convert parameter number from 'std::pair<_Ty1,_Ty2>' to 'const void*'"

. What is a mistake?

This question is tagged with c++

~ Asked on 2013-06-03 10:29:40

The Best Answer is


32

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
  return lhs.first < rhs.first;
}

~ Answered on 2013-06-03 10:34:22


31

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

~ Answered on 2013-06-03 10:50:26


Most Viewed Questions: