Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 522
vard Avatar asked Jun 03 '13 10:06

vard


People also ask

How do you create a compare function in C++?

String strcmp() function in C++ C++ String has got in-built functions to manipulate and deal with data of string type. In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner.

What does std::sort do C++?

std::sort() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also​ be used for custom sorting by passing in a comparator function that returns a boolean.

What method does std::sort use?

The std::sort is a sorting function that uses the Introsort algorithm and have the complexity of O(N log(N)) where N= std::distance(first, last) since C++11 and the order of equal elements is not guaranteed to be preserved[3]. The gcc-libstdc++ also uses Introsort algorithm.

Is std::sort fast?

In general, std::sort is indeed faster than qsort because of a couple of these things: qsort operates on void* , which first requires a dereference, and second requires the size of the data type to perform the swaps.


1 Answers

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; }); 
like image 129
Felix Glas Avatar answered Sep 22 '22 19:09

Felix Glas