STL5:仿函数
1、概念
模仿函数的类,使用方式如同函数。本质是类中重载括弧运算符operator()。
2、场景
不同函数复用相同处理代码。
3、使用
3.1 C语言的处理方式
使用函数指针和回调函数来实现代码复用。例如qsort()
#include <stdio.h>
#include <stdlib.h>
int arr_sort(const void *a,const void *b){
return *(int *)a-*(int *)b;
}
int main(){
int arr[5]={
4,1,2,5,6};
qsort(arr,5,sizeof(arr[0]),arr_sort);
int i;
for(i=0;i<5;i++){
printf("%d\n",arr[i]);
}
return 0;
}
3.2 C++语言的处理方式
(1)函数指针方式
#include<iostream>
#include<algorithm>
using namespace std;
inline bool Sort(int a,int b){
return a > b;
}
inline void Display(int a){
cout << a << endl;
}
int main(){
int arr[]={
4,1,2,5,6};
sort(arr,arr+5,Sort);
for_each(arr,arr+5,Display);
return 0;
}
(2)函数模板方式
#include<iostream>
#include<algorithm>
using namespace std;
template<class T>
inline bool Sort(T const& a,const &b){
return a<b;
}
template<class T>
inline void