我正在学习如何使用仿函数,所以我创建了一个,我不明白为什么我的计数器变量在程序结束时为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;
}
以下是结果:
in the functor: 1 counter=1
in the functor: 2 counter=2
in the functor: 3 counter=3
in the functor: 4 counter=4
in the functor: 5 counter=5
in the functor: 6 counter=6
in the functor: 7 counter=7
in the functor: 8 counter=8
in the functor: 9 counter=9
in the functor: 10 counter=10
counter=0
答案 0 :(得分:8)
如果您查看for_each
的签名,您会看到它按值接受仿函数,因此您在for_each
内看到的更改在算法终止时不会反映在外部。
http://en.cppreference.com/w/cpp/algorithm/for_each
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
如果你想做这项工作,你将不得不使用std::ref
生成一个引用包装器并按值传递它。
std::for_each(vec.begin(), vec.end(), std::ref(functor));
查看documentation for std::ref
和reference_wrapper
,看看其工作原理和原因(关键点是std::reference_wrapper
有一个operator()
来处理仿函数{{ 3}})。
答案 1 :(得分:0)
答案 2 :(得分:0)
虽然Curious的答案是最好的解决方案,但这是另一个:
class myFunctor {
public:
myFunctor():counter(std::make_shared<int>(0)) {}
void operator()(int i) { cout << "in the functor: " << i ; ++*counter; cout << " counter=" << *counter << endl; }
int getCounter() const { return *counter; }
private:
std::shared_ptr<int> counter;
};