Re: I'd like to use STL algorithms
Greg Herlihy wrote:
imbunche wrote:
The following code applys a conversion function to elements
on a vector depending on its index, as follows:
int i;
vector<sometype> val;
for (i=0; i<tokens.size(); ++i)
{
val[i] = convert(i,v[i]);
// or ... val.push_back(convert(i,v[i]));
}
The best I have achieved (with my limited STL knowledge is:
transform(tokens.begin(), tokens.end(),
back_inserter(val), // where to put results.
bind (convert,
0, _1));
Which is useless of course becauss it fixes the first parameter of
convert to 0, ... I need some kind of i++ but I cannot find the way
....
I think that std::accumulate could be used to solve this
problem.
His problem modifies every element in an array. std::accumulate
in non-mutating with regards to the sequence it receives. You
could probably come up with some sort of accumulator type or
operator which contains a reference to the vector, and modifies
it, but that's more obfuscation than anything else.
His iteration actually involves the numerical value of the
index. As such, any conversion to the STL is likely to be
obfuscation, or at least more work, requiring that he maintain
the index manually anyway. In general, when the numerical value
of the index is significant, the STL (nor any other library
based on iterators) is not the answer.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]