The sort function uses a custom comparison function to implement customized sorting: write a comparison function: specify the sorting rules, define parameter types and return values. Call the sort function: pass the custom comparison function as the third parameter to sort the elements in the container. Example: Sort integers in descending order and strings according to custom rules (empty string first, length first, lexicographic order).
How to use the sort function in C to implement customized sorting function
sort
function is an important function in the C standard library, used to sort The elements in the container are sorted. It receives a comparison function by reference, allowing the user to sort elements based on custom criteria.
The syntax of comparison function
The syntax of comparison function is as follows:
bool compare(const T1& a, const T2& b);
Among them:
and
T2 are the element types to be compared.
means
a is less than
b.
means
a is greater than or equal to
b.
Implementing a custom sort
To implement a custom sort using thesort function, you need to write a custom comparison function that specifies the sorting behavior . Here is an example:
#include <algorithm> #include <vector> using namespace std; bool compareIntsDescending(int a, int b) { return a > b; } int main() { vector<int> numbers = {1, 5, 2, 4, 3}; sort(numbers.begin(), numbers.end(), compareIntsDescending); for (auto& num : numbers) { cout << num << " "; } cout << endl; return 0; }
Output of this program:
5 4 3 2 1
compareIntsDescending comparison function converts integers from large to small Sort.
Practical case: Sorting strings by custom rules
Suppose you have an array of strings and you want to sort them according to the following rules:
bool compareStrings(string a, string b) { // 检查是否为空字符串 if (a.empty() && !b.empty()) { return true; } else if (!a.empty() && b.empty()) { return false; } // 空字符串相等 if (a.empty() && b.empty()) { return false; } // 比较长度 if (a.length() < b.length()) { return true; } else if (a.length() > b.length()) { return false; } // 长度相同时按字母顺序比较 return (a < b); }
#include <algorithm> #include <vector> using namespace std; int main() { vector<string> strings = {"apple", "banana", "cherry", "dog", "cat", ""}; sort(strings.begin(), strings.end(), compareStrings); for (auto& str : strings) { cout << str << " "; } cout << endl; return 0; }
Output of this program:
dog cat apple banana cherry
The above is the detailed content of How to correctly use the C++sort function to implement customized sorting function. For more information, please follow other related articles on the PHP Chinese website!