我正在学习如何使用仿函数,所以我创建了一个,我不明白为什么我的计数器变量在程序结束时为0.
这里的代码:
#include"stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<list>
using namespace std;
class myFunctor {
public:
myFunctor():counter(0) {}
void operator()(int i) { cout << "in the functor: " << i ; counter++; cout << " counter=" << counter << endl; }
int getCounter() const { return counter; }
private:
int counter;
};
int main()
{
vector<int> v{ 1,2,3,4,5,6,7,8,9,10 };
myFunctor f;
for_each(v.begin(), v.end(), f);
cout << "counter=" << f.getCounter() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
in the functor: 1 counter=1
in …Run Code Online (Sandbox Code Playgroud)