C++中的sort函数怎么用

   2025-02-13 9510
核心提示:在C++中,可以使用std::sort函数对数组或容器中的元素进行排序。std::sort函数属于algorithm头文件,使用前需要包含该头文件。st

在C++中,可以使用std::sort函数对数组或容器中的元素进行排序。std::sort函数属于<algorithm>头文件,使用前需要包含该头文件。

std::sort函数有两种使用方式:

排序数组:可以使用std::sort函数对数组中的元素进行排序。例如:
#include <algorithm>#include <iostream>int main() {    int arr[] = {5, 2, 8, 1, 9};    std::sort(arr, arr + 5);  // 对数组元素进行排序    for (int i = 0; i < 5; ++i) {        std::cout << arr[i] << " ";    }    return 0;}

输出结果为:1 2 5 8 9

排序容器:可以使用std::sort函数对容器中的元素进行排序。例如:
#include <algorithm>#include <iostream>#include <vector>int main() {    std::vector<int> vec = {5, 2, 8, 1, 9};    std::sort(vec.begin(), vec.end());  // 对容器元素进行排序    for (int i = 0; i < vec.size(); ++i) {        std::cout << vec[i] << " ";    }    return 0;}

输出结果为:1 2 5 8 9

std::sort函数默认按照升序对元素进行排序。如果需要按照降序排序,可以使用自定义的比较函数。例如:

#include <algorithm>#include <iostream>#include <vector>bool compare(int a, int b) {    return a > b;}int main() {    std::vector<int> vec = {5, 2, 8, 1, 9};    std::sort(vec.begin(), vec.end(), compare);  // 按照自定义的比较函数对容器元素进行排序    for (int i = 0; i < vec.size(); ++i) {        std::cout << vec[i] << " ";    }    return 0;}

输出结果为:9 8 5 2 1

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言