Re: I'd like to use STL algorithms
kanze wrote:
I'd say that when you are dealing with indexes, random access is
sort of implied. If I were to translate the above into C++, I'd
write something like:
for ( C::iterator i = c.begin() ; i != c.end() ; ++ i ) {
*i = convert( *i, std::distance( c.begin(), i ) ) ;
}
This will work even on an std::list, but if the list is long,
it's likely to be rather slow.
And the point is that of course, the convert function being used
depends on the position of the object in the container, not on
some arbitrary additional integral value which just happens to
correspond to the position in this case.
It seems that what's really going on here is that the vector is used
as a map from integers to tokens, rather than as a collection of
tokens that just happens to be randomly accessible. Consider
std::map<S, T> tokens;
Container<X> val;
// original
X convert(std::pair<S, T> token) {
// ...
}
for (i = 0; i < tokens.size(); ++i) {
val[i] = convert(i, tokens[i]);
}
// STL
struct convert {
X operator()(std::pair<S, T> token) {
// ...
}
}
std::transform(tokens.begin(), tokens.end(),
back_inserter(val), convert());
A random access container can be seen as a pair associative container
or as a unique associative container. I'd make a
random-access-container-as-pair-unique-associative-container function
so that we could write:
std::transform(rac_as_puac(tokens).begin(),
rac_as_puac(tokens).end(),
back_inserter(val), convert());
rac_as_uac would return an object of a type that is a model of the
pair associative container and unique associative container concepts,
but rather than storing its own data, keeps a pointer or reference to
the argument and forwards appropriately.
Lourens
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]