std::sort()

定义

template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

作用:

Sorts the elements in the range [first,last) into ascending ↑(when comp is nullptr) order.

comp函数说明:


Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
当函数返回true时,认为第一个参数在第二个参数之前(第一个参数的索引值小)


The function shall not modify any of its arguments.
This can either be a function pointer or a function object.


引自---cplusplus.com

实验:

源码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool comp1(int a,int b) {
    return b>a;
}
bool comp2(int a,int b) {
    return a>b;
}
int main() {
    int arr[] = {1,2,3,9,8,7};
    cout<<"sort by comp1 (ascending):"<<endl;
    sort(arr,arr+6,comp1);
    for(int i:arr) {
        cout<<i<<endl;
    }
    cout<<"sort by comp2 (descending):"<<endl;
    sort(arr,arr+6,comp2);
    for(int i:arr) {
        cout<<i<<endl;
    }
    return 0;
}

输出:

image

posted @ 2021-08-09 17:01  niu_a  阅读(129)  评论(0编辑  收藏  举报