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