Home >Backend Development >C++ >Detailed explanation and example demonstration of C++sort function
Summary: The C sort function is used to sort container elements. By default, it sorts in ascending order using the
C Detailed explanation and example demonstration of sort function
sort function overview
sort function is a powerful function in the C Standard Template Library (STL) for sorting container elements. It arranges the elements in a container into ascending or descending order based on specified comparison rules.
The function is declared as follows:
template<typename Iter> void sort(Iter first, Iter last);
Among them:
Custom comparison rules
By default, the sort function uses the operator for comparison, which means it will Container elements are sorted in ascending order. If you wish to sort according to different rules, you can provide a custom comparison function:
bool compare(const Type1& a, const Type2& b) { // 自定义比较规则 } // 在 sort 函数中使用自定义比较函数 sort(first, last, compare);
Practical case
Example 1: Sorting an array of integers
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {5, 2, 7, 1, 3}; int len = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + len); cout << "排序后的数组:"; for (int i = 0; i < len; i++) { cout << " " << arr[i]; } cout << endl; return 0; }
Output:
排序后的数组: 1 2 3 5 7
Example 2: Sorting an array of strings
#include <iostream> #include <algorithm> using namespace std; int main() { string arr[] = {"apple", "orange", "banana", "kiwi", "mango"}; int len = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + len); cout << "排序后的数组:"; for (int i = 0; i < len; i++) { cout << " " << arr[i]; } cout << endl; return 0; }
Output:
排序后的数组: apple banana kiwi mango orange
The above is the detailed content of Detailed explanation and example demonstration of C++sort function. For more information, please follow other related articles on the PHP Chinese website!