版本比较

标识

  • 该行被添加。
  • 该行被删除。
  • 格式已经改变。

std::sort()

原型:

代码块
#include <algorithm>

template< class RandomIt >
void sort( RandomIt first, RandomIt last );

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

用于将范围 [first, last) 内的元素按升序排序。不稳定排序,相同的元素位置可能被打乱。

默认使用 operator< 进行排序,也可以提供一个自定义的比较函数comp,要求函数签名如下:
bool comp(const Type1 &a, const Type2 &b);
比较时a表示后面的元素,b表示前面的元素,要求comp(a, b)返回false。

使用示例:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

static void print(vector<int> &a) {
    for(auto i : a) {
        cout << i << " ";
    }
    cout << "\n";
}

static bool less(int a, int b) {
    return a < b;
}

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

int main() {
    vector<int> a = {-1, 1, 2, 0, 3, 2, 0, 5};

    sort(a.begin(), a.end()); //默认升序
    print(a);

    random_shuffle(a.begin(), a.end());
    sort(a.begin(), a.end(), less); //使用less进行元素比较,升序
    print(a);

    random_shuffle(a.begin(), a.end());
    sort(a.begin(), a.end(), customLess); //使用customLess进行元素比较,降序
    print(a);

    random_shuffle(a.begin(), a.end());
    sort(a.begin(), a.end(),[](int a, int b){ //使用lambada函数,升序
        return a < b;
    });
    print(a);

    random_shuffle(a.begin(), a.end());
    sort(a.begin(), a.end(), std::less<int>()); //使用标准库比较对象,升序
    print(a);

    random_shuffle(a.begin(), a.end());
    sort(a.begin(), a.end(), std::greater<int>()); //使用标准库比较对象,降序
    print(a);

    return 0;
}

std::reverse()
用于翻转或部分翻转顺序容器的数据,例如:
vector<int> v;
...
reverse(v.begin() + 5, v.begin() + 8);  //翻转第6至第9区间内的元素

std::min_element()
给定区间的最小值,示例:

#include <algorithm>
#include <iostream>
#include <vector>int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9};
    std::vector<int>::iterator result = std::min_element(v.begin(), v.end());
    std::cout << "min element at: " << std::distance(v.begin(), result);
}

显示子页面