partial_sort

partial_sort是C++STL中的函式。

函式簡介,函式實現原理,函式套用舉例,

函式簡介

函式原型有:
partial_sort(beg,mid,end)
partial_sort(beg,mid,end,comp)
函式作用:
對mid-beg個元素進行排序,也就是說,如果mid-beg等於42,則該函式將有序次序中的最小值元素放在序列中
的前42個位置。partial_sort完成之後,從beg到mid(但不包括mid)範圍內的元素是有序的,已排序範圍內沒有元素大於mid之後的元素。未排序元素之間的次序是未指定的。

函式實現原理

partical_sort的原理是堆排序!
首先創建一個堆,得到最大值。如果要得到次大值,就將頭結點去掉,即調用pop_heap(),此時的頭結點就是
次大值,可以這樣依次得到最大或者最小的幾個值!

函式套用舉例

#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <time.h>
using namespace std;
int rand_int()
{
return rand()%100;
}
void print(vector<int> &v,const char* s)
{
cout<<s<<endl;
copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
cout<<endl;
}
bool cmp(int &a, int &b)
{
if(a>b)
return true;
return false;
}
class compare{
public:
bool operator()(const int &a,const int &b)
{
if(a<b)
return true;
return false;
}
};
int main()
{
srand(time(NULL));

相關詞條

熱門詞條

聯絡我們