传智扫地僧课程学习笔记。
这是老师课上示例代码,
看了两遍,还有点不习惯,
#include <iostream>
using namespace std;
#include "string"
#include <vector>
#include <list>
#include "set"
#include <algorithm>
#include "functional"
//函数对象 类重载了()
template <typename T>
class ShowElemt
{
public:
ShowElemt()
{
n = 0;
}
void operator()(T &t)
{
n ++;
//printN();
cout << t << " ";
}
void printN()
{
cout << "n:" << n << endl;
}
protected:
private:
int n;
};
//函数模板 ==函数
template <typename T>
void FuncShowElemt(T &t)
{
cout << t << endl;
}
//普通函数
void FuncShowElemt2(int &t)
{
cout << t << " ";
}
//函数对象 定义 ; 函数对象和普通函数的异同
//
void main01()
{
int a = 10;
ShowElemt<int> showElemt;
showElemt(a); //函数对象的()的执行 很像一个函数 //仿函数
FuncShowElemt<int>(a);
FuncShowElemt2(a);
}
//函数对象是属于类对象,能突破函数的概念,能保持调用状态信息
//函数对象的好处
// for_each算法中, 函数对象做函数参数
// for_each算法中, 函数对象当返回值
void main02()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
for_each(v1.begin(), v1.end(), ShowElemt<int>()); //匿名函数对象 匿名仿函数
cout << endl;
for_each(v1.begin(), v1.end(), FuncShowElemt2); //通过回调函数 谁使用for_each 谁去填写回调函数的入口地址
ShowElemt<int> show1;
//函数对象 做函数参数
/*
template<class _InIt,
class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Func);
return (_For_each(_Unchecked(_First), _Unchecked(_Last), _Func));
}
*/
//1 for_each算法的 函数对象的传递 是元素值传递 ,不是引用传递
for_each(v1.begin(), v1.end(), show1);
show1.printN();
cout << "通过for_each算法的返回值看调用的次数" << endl;
show1 = for_each(v1.begin(), v1.end(), show1);
show1.printN();
//结论 要点: 分清楚 stl算法返回的值是迭代器 还是 谓词(函数对象) 是stl算法入门的重要点
}