Re: I'd like to use STL algorithms
imbunche wrote:
Hi,
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. For
example, I would first declare a function (or a function object) that
accepts an index value and a reference to a "sometype" type as
parameters, and which returns the accumulated value (serving as the
index) incremented by one:
int AccumulateProc(int acc, sometype& t)
{
t = convert(acc, t);
return acc+1;
}
And then pass this routine (or object) to std::accumlate like so:
#include <vector>
#include <numeric>
...
std::vector<sometype> v;
...
int acc;
acc = accumulate( v.begin(), v.end(), 0, AccumulateProc);
The sometype elements in the vector will have been converted in place.
Note that for this code to compile, sometype must be assignable (that
is, it may be necessary implement operator=() for sometype's).
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]