摘要:c++++ sort 函数用于对容器元素进行排序。默认情况下,它使用 字符串数组进行排序。
C++ 排序函数详解与示例演示
sort 函数概述
sort 函数是 C++ 标准模板库 (STL) 中一个强大的函数,用于对容器元素进行排序。它根据指定的比较规则将容器中的元素排列成升序或降序。
立即学习“C++免费学习笔记(深入)”;
函数声明如下:
template<typename Iter> void sort(Iter first, Iter last);
其中:
自定义比较规则
默认情况下,sort 函数使用
bool compare(const Type1& a, const Type2& b) { // 自定义比较规则 } // 在 sort 函数中使用自定义比较函数 sort(first, last, compare);
实战案例
示例 1:对整数数组排序
#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; }
输出:
排序后的数组: 1 2 3 5 7
示例 2:对字符串数组排序
#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; }
输出:
排序后的数组: apple banana kiwi mango orange
以上就是C++sort函数详解与示例演示的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号