之前写过c++sort函数可以自定义排序方式自定义sort函数,感到很神奇,最近突然灵光一现,明白了它的实现原理
在这里我们通过自定义一个比较函数实现了sort的逆序排序:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool revesal(int, int);
int main()
{
vector<int > arr{ 4,6,2,1,6,7,4,3 },arr1=arr,arr2=arr;
sort(arr1.begin(), arr1.end());
for (auto a : arr1) cout << a << ends;
cout << endl;
sort(arr2.begin(), arr2.end(),revesal);//自定义操作
for (auto a : arr2) cout << a << ends;
cout << endl;
return 0;
}
bool revesal(int num1,int num2) {
return num1 > num2;
}
下面开始着手实现这样可以自定义操作的函数
#include <iostream>
using namespace std;
bool defaule(int, int);
void sort(int*, int*,bool (*)(int,int)=defaule);
bool revesal(int, int);
int main()
{
int arr1[]={ 4,6,2,1,6,7,4,3 },arr2[]= { 4,6,2,1,6,7,4,3 };
sort(begin(arr1), end(arr1));
for (auto a : arr1) cout << a << ends;
cout << endl;
sort(begin(arr2), end(arr2),revesal);
for (auto a : arr2) cout << a << ends;
cout << endl;
return 0;
}
void sort(int* begin, int* end, bool (*way)(int, int)) {
for (auto i = begin; i != end; ++i)
for (auto j = i + 1; j != end; ++j)
if (way(*i, *j)) swap(*i, *j);
}
bool defaule(int num1, int num2) {
return num1 < num2;
}
bool revesal(int num1,int num2) {
return num1 > num2;
}
看来可以自定义的函数就是通过函数指针来实现的,有时相关操作所需的参数多余定义时的参数怎么办,比如sort排序函数需要将值与我们希望的一个值比较,大于它才交换,这时可以用c++中的lambda表达式实现
#include <iostream>
#include <algorithm>
using namespace std;
bool revesal(int,int);
int main()
{
int arr1[]={ 4,6,2,1,6,7,4,3 },arr2[]= { 4,6,2,1,6,7,4,3 },a=5;
sort(begin(arr1), end(arr1),revesal);
for (auto a : arr1) cout << a << ends;
cout << endl;
sort(begin(arr2), end(arr2), [a](int num1, int num2)->bool {
return num1 > num2 && num1 > a;
});
for (auto a : arr2) cout << a << ends;
cout << endl;
return 0;
}
bool revesal(int num1,int num2) {
return num1 > num2;
}
但我们自定义的sort函数却不能用lambda表达式,看来这不仅仅是函数指针了,可能有一个接受lambda对象的重载函数,具体实现看来我还要一段时间才能弄明白