[Please do not mail me a copy of your followup]
Doug Mika <
doug...@gmail.com> spake the secret code
<
a7ca7647-b5c0-4d5a...@googlegroups.com> thusly:
The functor is copied around by for_each, so the one it uses is not
the one that you declared locally, it's a copy. This is implied by
the signature of for_each which takes the functor by value. To get
what you want, you have to use a referring wrapper like boost::ref, or
have your functor reference the count held elsewhere:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
struct DisplayElementKeepCount{
int &Count;
DisplayElementKeepCount(int &Storage):Count(Storage){}
void operator()(const T& element){
++Count;
cout<<element<<' ';
}
};
int main(int argc, char** argv) {
//The Program
vector<int> vecIntegers;
for(int nCount=0;nCount<10; ++nCount)
vecIntegers.push_back(nCount);
int Count = 0;
DisplayElementKeepCount<int> Result(Count);
cout<<"Displaying the vector of integers again"<<endl;
for_each(vecIntegers.begin(),vecIntegers.end(),Result);
cout<<endl<<endl;
cout<<"The Result count this time is: "<<Result.Count<<endl;
return 0;
}
--
"The Direct3D Graphics Pipeline" free book <
http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <
http://computergraphicsmuseum.org>
The Terminals Wiki <
http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <
http://legalizeadulthood.wordpress.com>