C++中排序函数sort的用法

C++中使用sort函数必须加上头文件"#include <algorithm>"。

sort函数的使用方式是:

sort(首元素地址, 尾元素地址的下一位,比较函数(选填))

 代码示例如下:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;

bool cmp(int a, int b) {
    return a>b;
}

int main() {
    vector<int> v;
    v.push_back(3);
    v.push_back(1);
    v.push_back(2);
    v.push_back(0);
    sort(v.begin(), v.end(), cmp);
    for (int i = 0; i < v.size(); i++) {
        printf("%d ", v[i]);
    }
    return 0;
}

结果为:3 2 1 0

猜你喜欢

转载自blog.csdn.net/qq_32273417/article/details/86708723