C++进阶STL-函数对象

函数对象的概念

  • 重载  ()操作符  的类,它的对象叫做函数对象,即它是 类似于函数的 对象(它可以向函数一样调用),也叫作仿函数。
    注意:函数对象(仿函数)是一个类,不是一个函数。

  • 重载操作符()有一个参数,称为一元仿函数,有两个参数,就叫二元仿函数。如果返回值是bool类型的函数对象或者普通函数,有一个参数叫做一元谓词

  • 函数对象做参数和返回值

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Print
{
	int num; // 保存运行的次数
	Print()
	{
		num = 0;
	}
	void operator()(int val)
	{
		cout << val << endl;
		num++;
	}
};
int main()
{
	Print myprint;

	vector<int> v1;
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);


	Print myprint2=for_each(v1.begin(), v1.end(), myprint); //遍历算法,函数对象作为参数,返回值也是函数对象

	cout << myprint2.num << endl; //打印出调用的次数,结果num=4
    return 0;
}


内建的函数对象 include<functional>

  • STL内建了一些函数对象,分为:
    算术类函数对象
    关系运算类
    逻辑运算类

用这些类的对象当做函数使用,用法与函数完全相同


1. 六个算术类 的函数对象,negate是一元,其他都是二元

  • template <class T>   T plus<T>  //加法的仿函数
  • template <class T>  T minute<T>  //减法的仿函数
  • template <class T>   T multiplies<T>  //乘法的仿函数
  • template <class T>   T divides<T>  //除法的仿函数
  • template <class T>   T modulus<T>  //取模(%)的仿函数
  • template <class T>   T negate<T>  //取反的仿函数
	plus <int> myplus;
	cout << myplus(20, 10) << endl;
//输出结果: 30

2. 六个关系运算类 的函数对象,都是二元运算

  • template<class T>  bool  equal_to <T>  //等于
  • template<class T>  bool  not_equal_to <T>  //不等于
  • template<class T>  bool  greater <T>  //大于
  • template<class T>  bool  greater_equal<T>  //大于等于
  • template<class T>  bool  less <T>  //小于
  • template<class T>  bool  less_equal <T>  //小于等于

3. 三个逻辑运算类 的函数对象,not是一元,其他都是二元运算

  • template<class T>  bool  logical_and <T>  //逻辑与
  • template<class T>  bool  logical_or <T>  //逻辑或
  • template<class T>  bool  logical_not <T>  //逻辑非

猜你喜欢

转载自blog.csdn.net/zzyczzyc/article/details/82952144