在C++中,对数组进行排序最常用且高效的方法是使用STL中的sort函数。它位于gorithm>头文件中,能够快速对普通数组或容器进行升序或降序排序,无需手动实现复杂的排序逻辑。
基本用法:对普通数组排序对于C风格的数组,sort函数通过传入起始和结束地址来工作。注意结束地址是“末尾后一位”,即使用指针表示时为arr + n。
示例:
#include <algorithm> #include <iostream> using namespace std; int main() { int arr[] = {5, 2, 8, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n); // 升序排序 for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } // 输出:1 2 5 8 9 return 0; }自定义排序规则:降序或特定条件
可以通过传入第三个参数——比较函数,来自定义排序顺序。比较函数返回bool值,表示第一个参数是否应排在第二个之前。
例如,实现降序排序:
bool cmp(int a, int b) { return a > b; // a排在b前面的条件 } sort(arr, arr + n, cmp);
也可以使用lambda表达式,更简洁:
sort(arr, arr + n, [](int a, int b) { return a > b; });对容器如vector排序
sort函数同样适用于STL容器,如vector、deque等。
#include <vector> #include <algorithm> using namespace std; vector<int> vec = {3, 7, 2, 5}; sort(vec.begin(), vec.end()); // 升序
对结构体或类对象排序时,可通过比较函数按指定字段排序:
struct Student { string name; int score; }; vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Cindy", 80}}; sort(students.begin(), students.end(), [](const Student& a, const Student& b) { return a.score > b.score; // 按分数降序 });
基本上就这些。熟练使用sort函数能大幅提高编码效率,避免手写冒泡或快排。关键是记住传参格式和比较函数的逻辑方向。不复杂但容易忽略细节。
以上就是C++数组排序算法 STL sort函数应用的详细内容,更多请关注知识资源分享宝库其它相关文章!
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。