C++使用sort函数对vector的任意区间排序(某一段元素排序)

    科技2025-09-25  72

    使用迭代器进行区间指定,注意start和end为前闭后开区间;sort函数内也可自行添加cmp比较函数,默认为从小到大排序。

    #include <vector> #include <algorithm> using namespace std; int main(){ vector<int>input = { 1, 5, 2, 1, 3, 2, 5 }; //排序整个vector //sort(input.begin(), input.end()); //对任意区间进行排序,同样使用迭代器 auto start = input.begin()+2;//下标对应2 auto end = start +3;//下标对应5 sort(start, end);//区间[2,5)进行排序 for (auto itr : input){ cout << itr << " "; } cout << endl; return 0; }

    运行结果如下

    Processed: 0.014, SQL: 8