也就是默认我们建的是大顶堆。
#include <iostream> // std::cout
#include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,5,15};
std::vector<int> v(myints,myints+5);
std::make_heap (v.begin(),v.end());
std::cout << "initial max heap : " << v.front() << '\n';
std::pop_heap (v.begin(),v.end()); v.pop_back();
std::cout << "max heap after pop : " << v.front() << '\n';
v.push_back(99); std::push_heap (v.begin(),v.end());
std::cout << "max heap after push: " << v.front() << '\n';
std::sort_heap (v.begin(),v.end());
std::cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++)
std::cout << ' ' << v[i];
std::cout << '\n';
return 0;
}
initial max heap : 30
max heap after pop : 20
max heap after push: 99
final sorted range : 5 10 15 20 99
当我们添加一个额外的参数时,
int main () {
int myints[] = {10,20,30,5,15};
std::vector<int> v(myints,myints+5);
std::make_heap (v.begin(),v.end(),greater<int>());
std::cout << "initial max heap : " << v.front() << '\n';
std::pop_heap (v.begin(),v.end(),greater<int>()); v.pop_back();
std::cout << "max heap after pop : " << v.front() << '\n';
v.push_back(99); std::push_heap (v.begin(),v.end(),greater<int>());
std::cout << "max heap after push: " << v.front() << '\n';
std::sort_heap (v.begin(),v.end(),greater<int>());
std::cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++)
std::cout << ' ' << v[i];
std::cout << '\n';
return 0;
}
initial max heap : 5
max heap after pop : 10
max heap after push: 10
final sorted range : 99 30 20 15 10
这样就是一个小顶堆,注意这里我们用的是greater<int>(),
默认的和用less<int>()一样的,建立的是大顶堆,最后元素时从小到大的顺序排列。
我们知道,我们传进去的函数对象,STL使用的时候,是用第一个参数和后一个参数,调用这个函数,用函数返回结果作为两者的比较结果。在堆上面,默认是大顶堆,也就是穿进去的函数对象是less<int>,也就是当父节点小于子节点时,函数返回true,然后因为返回true,所以就做处理,也就是交换父子节点。也就是说当判定结果为真时,就执行操作。
void swap(int *p,int a,int b){
int temp = p[a];
p[a] = p[b];
p[b] = temp;
}
void quicksort(int v[],int n)
{
int i,last;
if (n<=1)
return;
swap(v,0,rand()%n);
last = 0;
for(i=1;i<n;i++)
if(v[i] < v[0])
swap(v,++last,i);
swap(v,0,last);
quicksort(v,last);
quicksort(v+last+1,n-last-1);
}
int main () {
int myints[] = {10,20,30,5,15};
quicksort(myints,5);
std::vector<int> v(myints,myints+5);
//sort(v.begin(),v.end(),greater<int>());
for (unsigned i=0; i<v.size(); i++)
std::cout << ' ' << v[i];
std::cout << '\n';
return 0;
}
根据以上代码我们可以发现猜测是正确的,当我们用< 操作符对两个元素做判断,当为真的时候作交换,然后得到的序列就是有序的升序序列。
其实我们可以发现,所有的算法默认用的都是less<T>.sort函数也是的,默认是less<int>,得到的结果是升序。