文章目录
1. 仿函数的基本用法
对于仿函数的使用需要:
- 创建一个类,类中要对 ( ) 运算符重载
- 创建函数,调用 ( ) 运算符重载,实现仿函数的使用
#include <iostream>
using namespace std;
void Func(int n){
cout << "Hello World" << n << endl;
}
class Functor{
public:
void operator () (int n){
cout << __func__ << n << endl;
}
};
int main(){
Func(1);
void (*pFunc)(int) = Func; // 定义函数指针
pFunc(2);
// 仿函数,函数对象
Functor func; // 先定义一个对象
func(3); // 调用了()运算符重载
func.operator()(4);
}
结果为:
Hello World1
Hello World2
operator()3
operator()4
2. 用于数组排序算法
2.1 sort 排序算法
对arr数组、vector容器内数据、list容器内数据排序
使用通用排序算法 sort
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
// 控制降序
bool cmp(int a,int b){
return a>b;
}
int main(){
// arr数组排序
int arr[] = {
2,3,1,5,4,6};
// sort(arr,arr+6);
sort(begin(arr),end(arr),cmp); // 不加cmp,默认升序
for(auto n:arr){
cout << n << " ";
}
cout << endl;
// vector排序
vector<int> c = {
2,3,1,5,4,6};
sort(c.begin(),c.end());
for(auto n:c){
cout << n << " ";
}
cout << endl;
// list排序
list<int> d = {
2,3,1,5,4,6};
d.sort(); // list有自己的排序方法sort
for(auto n:d){
cout << n << " ";
}
cout << endl;
}
结果为:
6 5 4 3 2 1
1 2 3 4 5 6
1 2 3 4 5 6
2.2 仿函数控制升降序
使用仿函数可以对数组的升降排序直接控制
#include <iostream>
#include <algorithm>
using namespace std;
// 控制降序
bool cmp(int a,int b){
return a>b;
}
class Compare{
bool asc;
public:
Compare(bool asc):asc(asc){
} // 构造函数
bool operator()(int a,int b)const{
// ()运算符重载
return asc?a<b:a>b;
}
};
int main(){
// 数组排序,使用仿函数
int arr[] = {
2,3,1,5,4,6};
int a