STL仿函数
STL中的仿函数的主要功能是为了搭配STL算法使用, 仿函数(functors)在C++标准中采用的名称是函数对象(function objects),在<functional>
头文件中定义了如下三类仿函数:
1. 算术类仿函数
操作 | 仿函数 |
---|
加 | plus<T> |
减 | minus<T> |
乘 | multiplies<T> |
除 | divides<T> |
取模 | modulus<T> |
取反 | negate<T> |
#include <iostream>
#include <numeric>
#include <functional>
using namespace std;
int main(){
int arr[]={1,2,3,4,5};
vector<int> iv(ia,ia+5);
cout<< accumulate(iv.begin(),iv.end(),1,multiplies<int>()) <<endl;
return 0;
}
cout<< accumulate(iv.begin(),iv.end(),1,_1*_2) <<endl;
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
inline void Print(int a){
cout << a << endl;
}
int main(){
int first[]={1,2,3,4,5};
int second[]={10,20,30,40,50};
int results[5];
transform (first, first+5, second, results, std::plus<int>());
for_each(results,results+5,Print);
return 0;
}
transform (first, first+5, second, results, _1+_2);
template<typename T>
struct plus{
T operator()(int a,int b){
return a+b;
}
};
template<typename T>
struct multiplies{
T operator()(int a,int b){
return a*b;
}
};
2. 关系运算类仿函数
操作 | 仿函数 |
---|
等于 | equal_to<T> |
不等于 | not_equal_to<T> |
大于 | greater<T> |
大于等于 | greater_equal<T> |
小于 | less<T> |
小于等于 | less_equal<T> |
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
inline void Print(int a){
cout << a << endl;
}
int main(){
int arr[]={1,2,3,4,5};
sort(arr,arr+5,greater<int>());
for_each(arr,arr+5,Print);
return 0;
}
sort(arr,arr+5,_1>_2);
template<typename T>
struct greater{
bool operator()(const T& a,const T& b){
return a>b;
}
};
template<typename T>
struct less{
bool operator()(const T& a,const T& b){
return a<b;
}
};
3. 逻辑运算仿函数
操作 | 仿函数 |
---|
逻辑与 | logical_and<T> |
逻辑或 | logical_or<T> |
逻辑否 | logical_not<T> |
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
inline void Print(bool a){
cout << a << endl;
}
int main () {
bool values[] = {true,false,true,false};
transform (values, values+4, values, logical_not<bool>());
cout.flags(ios::boolalpha);
for_each(values, values+4,Print);
return 0;
}
transform (values, values+4, values, !_1);
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
inline void Print(bool a){
cout << a << endl;
}
int main () {
bool values1[] = {true,false,true,false};
bool values2[] = {false,true,false,true};
bool result[4];
transform(values1, values1+4,values2, result, logical_and<bool>());
cout.flags(ios::boolalpha);
for_each(result,result+4,Print);
return 0;
}
transform(values1, values1+4,values2, result, _1 and _2);