1.仿函数在STL中的定义
要使用STL内建的仿函数,必须包含functional头文件。
1.Arithmetic operations
- 加:plus
- 减:minus
- 乘:multiplies
- 除:divides
- 求余数:modulus
- 否定:negate
源代码
#include <iostream>
#include <numeric>
#include <vector>
#include <functional>
using namespace std;
int main()
{
int ia[]={1,2,3,4,5};
vector<int> iv(ia,ia+5);
cout<<accumulate(iv.begin(),iv.end(),1,multiplies<int>())<<endl; //求取5*4*3*2,记住它的调用方式
cout<<multiplies<int>()(3,5)<<endl;
modulus<int> modulusObj;
cout<<modulusObj(3,5)<<endl; // 计算3%5的余数
return 0;
}
运行结果
关于里面accumlate的例子
// accumulate example
#include <iostream> // std::cout
#include <functional> // std::minus
#include <numeric> // std::accumulate
int myfunction (int x, int y) {return x+2*y;}
struct myclass {
int operator()(int x, int y) {return x+3*y;}
} myobject;
int main () {
int init = 100;
int numbers[] = {10,20,30};
std::cout << "using default accumulate: ";
std::cout << std::accumulate(numbers,numbers+3,init);
std::cout << '\n';
std::cout << "using functional's minus: ";
std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
std::cout << '\n';
std::cout << "using custom function: ";
std::cout << std::accumulate (numbers, numbers+3, init, myfunction); //①
std::cout << '\n';
std::cout << "using custom object: ";
std::cout << std::accumulate (numbers, numbers+3, init, myobject); //②
std::cout << '\n';
return 0;
}
对于①,myfunction函数的两个参数(x,y),x=init;y=*number。每一次init=myfunction的返回值,同时y=*(number+1);
对于②,同理于①
运行结果
modulus在cplusplus中的定义
2.关系运算类仿函数
等于:equal_to
不等于:not_equal_to
大于:greater
大于等于:greater_equal
小于:less
小于等于:less_equal
从大到小排序:
#include <iostream>
#include <algorithm>
#include <vector>
#include<functional>
using namespace std;
template <class T>
class display
{
public:
void operator()(const T &x)
{
cout<<x<<" ";
}
};
int main()
{
int ia[]={1,5,4,3,2};
vector<int> iv(ia,ia+5);
sort(iv.begin(),iv.end(),greater<int>());
for_each(iv.begin(),iv.end(),display<int>());
return 0;
}