6 STL仿函数
6.1 概念
模仿函数的类,使用方式如同函数。本质是类中重载括弧运算符operator()
。
6.2 场景
不同函数复用相同处理代码。
6.3. 使用
6.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("%i\n", arr[i]);
}
return 0;
}
6.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[5] = { 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,T const& b){
return a > b;
}
template<class T>
inline void Display(T a){
cout << a << endl;
}
int main() {
int arr[5] = { 4, 1, 2, 5, 6 };
sort(arr, arr+5,Sort<int>);
for_each(arr,arr+5,Display<int>);
return 0;
}
3、仿函数方式
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
class Compare{
int asc;
public:
Compare(bool asc):asc(asc){}
bool operator()(int a,int b){
return asc>0?a>b:a<b;
}
};
int main(){
int arr[] = {1,4,2,3,7,5};
for(auto p:arr){
cout << p << " ";
}
cout << endl;
//sort(arr,arr+6);
//sort(begin(arr),end(arr));
int asc;
cin >> asc; //根据输入数值进行排序
//定义仿函数,也称函数对象
Compare p(asc);
sort(begin(arr),end(arr),p);
for(auto p:arr){
cout << p << " ";
}
cout << endl;
cout << "---------list-----------" << endl;
list<int> li = {1,4,2,3,5};
for(auto p:li){
cout << p << " ";
}
cout << endl;
li.sort();
for(auto p:li){
cout << p << " ";
}
cout << endl;
}
1 4 2 3 7 5
1
7 5 4 3 2 1
---------list-----------
1 4 2 3 5
1 2 3 4 5
4、仿函数模板方式
template<class T>
class Sort{
public:
inline bool operator()(T const& a,T const& b) const {
return a > b;
}
};
template<class T>
class Display{
public:
inline void operator()(T const& a) const{
cout << a << endl;
}
};
int main()
{
int arr[5] = { 4, 1, 2, 5, 6 };
sort(arr, arr+5,Sort<int>());
for_each(arr,arr+5,Display<int>());
return 0;
}