<algorithm>中的sort()函数

来源:互联网 发布:服务器如何开放端口 编辑:程序博客网 时间:2024/06/08 16:16

迭代器iterator
begin()返回一个iterator 它指向容器的第一个元素
end()返回一个iterator 它指向容器的末元素的下一个位置

sort函数:前两个参数是两个指针(记为分别指向元素a和元素b),最后一个参数是一个比较函数,默认比较函数返回值为真时,将a到b之间的数从小到大排列;前两个参数为[a,b),即包含元素a,不包含元素b

#include <iostream>#include <algorithm>#include <vector>using namespace std;#define ElemType intbool less_than(ElemType a, ElemType b) {    return a > b;}int main() {    vector<ElemType> A;    ElemType B[20];    for (int i = 0; i < 20; i++) {        A.push_back(i);        B[i] = i;    }    sort(A.begin(), A.end(), less_than);    sort(B, B + 20, less_than);    vector<ElemType>::iterator it;    for (it = A.begin(); it != A.end(); it++) {        cout << (*it) << " ";    }    cout << endl;    for (int i = 0; i < 20; i++) {        cout << B[i]<<" ";    }    cout << endl;    return 0;}

运行结果

原创粉丝点击