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;
}