為了實作自定義資料類型(或者是内置資料類型)按照自己的排序規則進行排序,我們需要自己定義排序函數,這就需要用到回調函數或者仿函數或者lambda表達式。
1、回調函數,直接上程式。
#include<iostream>
#include<algorithm>
#include<vector>
#include<utility>
using namespace std;
//回調函數
bool func (pair<int, int >& a, pair<int, int >& b)
{
if (a.second != b.second)//如果第二個數不想打呢個,按照第二個數從小到大排序
return a.second < b.second;
return a.first < b.first;//否則相同的按照第一個從小到大排序
}
int main()
{
vector<pair<int, int>> ret;
pair<int, int >p(1,0);
pair<int, int >p1(1,5);
pair<int, int >p2(0, 5);
pair<int, int >p3(2, 5);
pair<int, int >p4(1, 4);
ret.push_back(p);
ret.push_back(p1);
ret.push_back(p2);
ret.push_back(p3);
ret.push_back(p4);
sort(ret.begin(), ret.end(), func);//回調函數
for(auto p:ret)
{
cout << p.first <<" "<< p.second << endl;
}
cout << endl;
return 0;
}
輸出結果:
//整體按照第二個數從小到大排序,第二個相等則按照第一個數從小到大排序
1 0
1 4
0 5//第二個都是5,按照第一個從小到大排序
1 5
2 5
2、仿函數,直接貼程式
#include<iostream>
#include<algorithm>
#include<vector>
#include<utility>
using namespace std;
//仿函數,重載小括号()
struct
{
bool operator() (pair<int, int >& a, pair<int, int >& b)
{
if (a.second != b.second)//這裡隻能用相等或者不等号,否則會出錯。
return a.second < b.second;
return a.first < b.first;
}
}cmp;
int main()
{
vector<pair<int, int>> ret;
pair<int, int >p(1,0);
pair<int, int >p1(1,5);
pair<int, int >p2(0, 5);
pair<int, int >p3(2, 5);
pair<int, int >p4(1, 4);
ret.push_back(p);
ret.push_back(p1);
ret.push_back(p2);
ret.push_back(p3);
ret.push_back(p4);
sort(ret.begin(), ret.end(), cmp);
for(auto p:ret)
{
cout << p.first <<" "<< p.second << endl;
}
cout << endl;
return 0;
}
輸出結果
1 0
1 4
0 5
1 5
2 5
3、lambda表達式,lambda表達式的用法:[](資料類型 a,資料類型 b){函數實作内容} 下面是用lambda表達式來定義自己的排序規則。
#include<iostream>
#include<algorithm>
#include<vector>
#include<utility>
using namespace std;
int main()
{
vector<pair<int, int>> ret;
pair<int, int >p(1,0);
pair<int, int >p1(1,5);
pair<int, int >p2(0, 5);
pair<int, int >p3(2, 5);
pair<int, int >p4(1, 4);
ret.push_back(p);
ret.push_back(p1);
ret.push_back(p2);
ret.push_back(p3);
ret.push_back(p4);
//lambda表達式定義排序規則
sort(ret.begin(), ret.end(),[](pair<int, int >a, pair<int, int >b)
{ if (a.second != b.second) return a.second < b.second; else return a.first < b.first;});
//輸出
for(auto p:ret)
{
cout << p.first <<" "<< p.second << endl;
}
cout << endl;
return 0;
}
輸出結果
1 0
1 4
0 5
1 5
2 5