Skip to main content
GameDev.net gamedev.net
🔒 Locked

Simple STL Question

Started by bakery2k1 Apr 10, 2005 at 3:41 PM 1 replies 800+ views
Original Post
bakery2k1
bakery2k1
I am working through Nicolai Josuttis' book on the C++ Standard Library, and am attempting to implement a simple functor. I have:

template<class T>
class Sum
{
public:
	Sum() : sum(0)
	{}

	void operator()(const T & elem)
	{ sum+=elem; }

	T sum;
};

int main()
{
	std::vector<int> coll;

	for(int i=0; i<5; ++i)
		coll.push_back(i);

	Sum<int> sum;

	for(std::vector<int>::const_iterator ci = coll.begin(); ci != coll.end(); ++ci)
		sum(*ci);

	std::cout << sum.sum << std::endl;
	
	return 0;
}
Does anyone know why this works, but replacing the for loop with:

	std::for_each(coll.begin(), coll.end(), sum);
means that the result is zero every time?
Fruny
Fruny
Because the functor is passed by value. You've got to grab the return value from std::for_each if you want the post-iteration functor:

sum = std::for_each(coll.begin(), coll.end(), sum);
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
me22
me22
I know it's not your question, but I'd like to point you to the accumulate function:
std::cout << std::accumulate( coll.begin(), coll.end(), static_cast<col1::value_type>(0) ) << std::endl;

Note that the return type is the same as the type of the third parameter, so if you say accumulate( my_floats.begin(), my_floats.end(), 0 ) you'll get very annoyed at the STL ( hence the explicit cast on 0 ).

Also, I don't think there's anything in the specs that prevents for_each from making a copy internally of the functor, so there's no way to make that idea work. ( Short of having Sum contain a reference to the variable to increment which would be set by the constructor, which is alot more work than just using accumulate... )

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.