why does my functor member variable "reset" ? (c++) -
i learning how use functors, , created one, , don't understand why counter variable 0 @ end of programm.
here code:
#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 functor: " << ; 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; }
here result gives:
in functor: 1 counter=1 in functor: 2 counter=2 in functor: 3 counter=3 in functor: 4 counter=4 in functor: 5 counter=5 in functor: 6 counter=6 in functor: 7 counter=7 in functor: 8 counter=8 in functor: 9 counter=9 in functor: 10 counter=10 counter=0
if take @ signature for_each
see accepts functor value, changes see inside for_each
not reflected outside when algorithm terminates.
http://en.cppreference.com/w/cpp/algorithm/for_each
template< class inputit, class unaryfunction > unaryfunction for_each( inputit first, inputit last, unaryfunction f );
if want make work going have use std::ref
generate reference wrapper , pass value.
std::for_each(vec.begin(), vec.end(), std::ref(functor));
take @ documentation std::ref
, reference_wrapper
see how , why works (the key point std::reference_wrapper
has operator()
work functors http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator()).
Comments
Post a Comment