Re: I'd like to use STL algorithms
Dan McLeran ha scritto:
template<typename T>
struct convert : public std::unaryfunctor<std::pair<int, T>, T>
{
public:
convert() : count(0){}
std::pair<int, T> operator()(T item) {
return std::make_pair(this->count++, ++item);
}
private:
int count;
};
You could then call transform like this:
transform(tokens.begin(), tokens.end(),
back_inserter(val), // where to put results.
convert<T>());
This approach calls for undefined behavior in the current C++ standard,
because binary_op is not allow to cause any side effects (in this case,
incrementing count is a side effect).
However, I just checked on comp.std.c++ that the situation is going to
be a bit different with the next C++ revision as this case will be
"demoted" from undefined to unspecified behavior. It's unspecified
because of two facts:
1) std::transform can make any number of copies of the binary_op and
that might interfere with keeping the count
2) the standard does not guarantee that the elements are processed in
order from the first to the last, so the count might mismatch the
traversed elements
The idea is that binary_op should be, as the name suggests, a binary
operator whose output depends uniquely from its input and not from any
stored state.
Ganesh
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]