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?
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.
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.
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.
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.
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 );
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With