c++-基础知识-案例-函数对象

本文介绍了C++中的函数对象(仿函数)及其使用,包括如何定义和调用函数对象,以及如何利用它们的状态和作为参数传递。此外,还讲解了谓词的概念,分为一元谓词和二元谓词,并展示了如何在算法中使用谓词进行条件查找和排序。最后,讨论了内建的算数仿函数如negate和plus的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c+±基础知识-案例-函数对象

1.函数对象基本使用

概念:

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

本质:

  • 函数对象(仿函数)是一个类,不是一个函数
#include <iostream>
#include <string>
//#include <vector>
//#include <deque>
//#include <map>
//#include <algorithm>
//#include <ctime>
using namespace std;

//函数对象基本使用
/*
*概念:
*重载函数调用操作符的类,其对象常称为函数对象
*函数对象使用重载的()时,行为类似函数调用,也叫仿函数
*本质:
*函数对象(仿函数)是一个类,不是一个函数
*/

//1.函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
class MyAdd
{
public:
	string operator()(string a,string b)
	{
		return a+b;
	}
};

//2.函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
	//构造函数
	MyPrint()
	{
		this->m_count = 0;
	}

	void operator()(string test)
	{
		cout<<test<<endl;
		this->m_count++;
	}
//状态
int m_count;

};

//3.函数对象可以作为参数传递

void test1(MyPrint &mp,string str)
{
	mp(str);
}

void test()
{
	//1
	cout<<"===test1==="<<endl;
	MyAdd ma;
	string str = ma("hello"," world!");
	cout<<str<<endl;
	//2
	cout<<"===test2==="<<endl;
	MyPrint mp;
	mp("test");
	mp("test");
	cout<<mp.m_count<<endl;
	//3
	cout<<"===test3==="<<endl;
	MyPrint mp1;
	test1(mp1,"test");
}
int main()
{
	test();
	return 0;
}

2.谓词

概念:

  • 返回bool类型德仿函数称为谓词
  • 如果operator()接受一个参数,那么叫做一元谓词
  • 如果operator()接受两个参数,那么叫做二元谓词
#include <iostream>
#include <string>
#include <vector>
//#include <deque>
//#include <map>
#include <algorithm>
//#include <ctime>
using namespace std;
//1.一元谓词
struct GreaterFive 
{
public:
	bool operator()(int val)
	{
		return val > 5;
	}
};
//2.二元谓词
struct MyCompare
{
public:
	bool operator()(int num1,int num2)
	{
		return num1 > num2;
	}
};
void test()
{
	//数组
	vector<int> v;
	for (int i = 0;i < 10; i++)
	{
		v.push_back(i);
	}
	//按照条件查找
	vector<int>::iterator it = find_if(v.begin(),v.end(),GreaterFive());
	if (it == v.end())
	{
		cout<<"没找到!"<<endl;
	}else{
		cout<<"找到:"<<*it<<endl;
	}
	//使用函数对象改变算法策略,排序从大到小
	sort(v.begin(),v.end(),MyCompare());
	
	for(vector<int>::iterator it = v.begin();it != v.end();it ++)
	{
		cout<<*it<<endl;
	}
}
int main()
{
	test();
	return 0;
}

3.内建函数对象-算数仿函数

功能描述

  • 实现四则运算
  • 其中negate是一元运算,其他都是二元运算

仿函数原型

template<class T> T plus<T>  //加法仿函数
template<class T> T negate<T>  //加法仿函数
#include <iostream>
#include <string>
#include <vector>
//#include <deque>
//#include <map>
#include <algorithm>
//#include <ctime>
#include <functional>
using namespace std;
void test()
{
	//1.negate函数
	negate<int>n;
	cout<<n(20)<<endl;;
	//2.plus函数
	plus<int>p;
	cout<<p(23,45)<<endl;
}
int main()
{
	test();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值