STL—— 函数对象(仿函数)

一、概念

1、函数对象的概念:

  • 重载函数调用操作符的类,其对象常称为函数对象。
  • 函数对象使用重载的()时,行为类似函数调用,也叫仿函数。
  • 函数对象(仿函数)是一个类,不是一个函数

2、函数对象使用

  • 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
  • 函数对象超出普通函数的概念,函数对象可以有自己的状态
  • 函数对象可以作为参数传递
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<ctime>
using namespace std;

class MyAdd
{
public:
	int operator()(int v1,int v2)
	{
		return v1 + v2;
	}
};

// 1、函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void Test01()
{
	MyAdd myadd;
	cout << myadd(10, 20) << endl;
}

// 2、函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
	MyPrint()
	{
		count = 0;
	}
	void operator()(string strContent)
	{
		cout << strContent << endl;
		count++;
	}
	int count;
};
void Test02()
{
	MyPrint myprint;
	myprint("this is just a test!");
	myprint("some test");
	cout << "myprint 被调用的次数为: " << myprint.count << endl;
}

// 3、函数对象可以作为参数传递
void DoPrint(MyPrint &mp,string test)
{
	mp(test);
}

void Test03() 
{
	MyPrint my;
	DoPrint(my, "hello this");
}

int main()
{
	Test01();
	Test02();
	Test03();
	system("pause");
}

二、谓词

  • 返回 bool 类型的仿函数称为谓词。
  • 如果 operator() 接受一个参数叫做一元谓词,两个参数叫做二元谓词。

1、一元谓词

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

class GetValue
{
public:
	bool operator()(int val)
	{
		return val > 5;
	}
};

void Test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
    
    // GetValue() 在此为隐式对象
	vector<int>::iterator it = find_if(v.begin(), v.end(),GetValue());
	if (it != v.end())
	{
		cout << "找到了大于5的值  = " << (*it) << endl;
	}
	else
	{
		cout << "未找到大于5的值" << endl;
	}
}

int main()
{
	Test01();

	system("pause");
}

三、内建函数对象

STL 中内建了一些函数对象。其分类为:

  • 算术仿函数
  • 关系仿函数
  • 逻辑仿函数

这些仿函数所产生的对象、用法和一般函数完全相同。使用内建函数对象,需要引入头文件  #include<functional>

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值