nth_element()

nth_element()排序是一个大致的排序,    nth_element(<#_RandomAccessIterator __first#>, <#_RandomAccessIterator __nth#>, <#_RandomAccessIterator __last#>, <#_Compare __comp#>)

里面有四个参数,分别是起始位置,排序位置,结束位置,排序规则(没有按默认排序),起始和结束都很好理解,那排序位置就是第i个位置的前面都小于a[i],后面都大于a[i],但不保证前后的数字是有序的

比如:

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

int main() {
    for (int i = 0; i < 10; i ++)
        a.push_back(i);
    random_shuffle(a.begin(), a.end());
    for (int i = 0; i < 10; i ++)
        printf("%d ", a[i]);
    printf("\n");
    nth_element(a.begin(), a.begin() + 5, a.end());
    for (int i = 0; i < 10; i ++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/henu_jizhideqingwa/article/details/81413388