函數名 | 功能描述 |
---|---|
sort | 對給定區間全部元素進行排序 |
stable_sort | 對給定區間全部元素進行穩定排序 |
partial_sort | 對給定區間全部元素部分排序 |
partial_sort_copy | 對給定區間複製並排序 |
nth_element | 找出給定區間的某個位置對應的元素 |
is_sorted | 判斷一個區間是否已經排好序 |
partition | 使得符合某個條件的元素放在前面 |
stable_partition |
相對穩定的使得符合某個條件的元素放在前面
|
1
2
3
4
|
bool complare(int a,int b)
{
return a>b;
}
|
#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a,int b)
{
return a>b;
}
int main()
{
int a[10]={9,6,3,8,5,2,7,4,1,0};
for(int i=0;i<10;i++)
cout<<a[i]<<endl;
sort(a,a+10,compare);//在這裏就不須要對compare函數傳入參數了,
//這是規則
for(int i=0;i<10;i++)
cout<<a[i]<<endl;
return 0;
}
假設本身定義了一個結構體node
struct node
{
int a;
int b;
double c;
}
有一個node類型的數組node arr[100],想對它進行排序:先按a值升序排列,若是a值相同,再按b值降序排列,若是b還相同,就按c降序排列。就能夠寫這樣一個比較函數:
如下是代碼片斷:
bool cmp(node x,node y)
{
if(x.a!=y.a) return x.a<y.a;
if(x.b!=y.b) return x.b>y.b;
return x.c>y.c;
}
|