c++中怎么用sort函数对给定区间排序

c++
1645
2024/4/8 16:09:50
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用std::sort函数对给定区间进行排序。下面是一个简单的示例代码:

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = {4, 2, 7, 5, 1, 3};

    std::cout << "Before sorting:" << std::endl;
    for(int i = 0; i < 6; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    std::sort(arr, arr + 6);

    std::cout << "After sorting:" << std::endl;
    for(int i = 0; i < 6; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

在这个示例中,我们首先定义了一个整型数组arr,然后使用std::sort函数对数组进行排序。std::sort函数接受两个迭代器参数,分别表示排序的起始位置和结束位置。在这个例子中,arr是一个数组,所以我们用arrarr+6分别表示数组的起始位置和结束位置。排序完成后,我们再次打印出排序后的数组元素。

需要注意的是,std::sort函数默认是按升序进行排序的。如果需要按照降序排序,可以使用std::greater<int>()作为第三个参数,例如std::sort(arr, arr + 6, std::greater<int>())

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++ string匹配能否实现多模式匹配