当前位置: 首页> 教育> 大学 > 搜索李晓峰_在线直播系统开发_站长工具网址查询_西安网站制作工作室

搜索李晓峰_在线直播系统开发_站长工具网址查询_西安网站制作工作室

时间:2025/7/12 2:56:38来源:https://blog.csdn.net/weixin_70149739/article/details/146769677 浏览次数:1次
搜索李晓峰_在线直播系统开发_站长工具网址查询_西安网站制作工作室

在 C++ 中,std::sort 是标准模板库(STL)中提供的一个非常高效的排序算法。它通常用于对容器中的元素进行排序,比如数组或 std::vectorstd::sort 默认按照升序排序,但你也可以通过提供自定义的比较函数或函数对象来实现降序或其他复杂排序逻辑。

基本用法

#include <iostream>
#include <vector>
#include <algorithm> // 包含 std::sortint main() {std::vector<int> numbers = {5, 2, 9, 1, 5, 6};// 默认升序排序std::sort(numbers.begin(), numbers.end());// 输出排序后的结果for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}


输出

1 2 5 5 6 9

降序排序

要实现降序排序,你可以使用 std::greater<int>() 作为第三个参数,或者使用自定义的比较函数。

使用 std::greater
 
#include <iostream>
#include <vector>
#include <algorithm>int main() {std::vector<int> numbers = {5, 2, 9, 1, 5, 6};// 降序排序std::sort(numbers.begin(), numbers.end(), std::greater<int>());// 输出排序后的结果for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}


自定义比较函数

你也可以定义一个自定义的比较函数:

#include <iostream>
#include <vector>
#include <algorithm>bool compareDescending(int a, int b) {return a > b; // 如果 a 大于 b,则 a 排在 b 前面
}int main() {std::vector<int> numbers = {5, 2, 9, 1, 5, 6};// 使用自定义比较函数进行降序排序std::sort(numbers.begin(), numbers.end(), compareDescending);// 输出排序后的结果for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}


注意事项

  1. 范围std::sort 的第一个和第二个参数是指定要排序的范围,通常是容器的 begin() 和 end() 迭代器。
  2. 稳定性std::sort 不保证稳定性,即对于相等的元素,排序后它们的相对顺序可能改变。如果需要稳定排序,可以使用 std::stable_sort
  3. 复杂度std::sort 的平均时间复杂度为 O(N log N),其中 N 是要排序的元素数量。

通过这些示例,你可以根据需求灵活使用 std::sort 对数据进行排序。

关键字:搜索李晓峰_在线直播系统开发_站长工具网址查询_西安网站制作工作室

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: