views:

112

answers:

1

How do I simplify this templated vector initializer loop using lambdas or some kind of STL transform?

template<typename T>
template<typename... Args>
void InitToRandomValues(vector<T>* retval, int n, RNG& rng, Args const&... args) {
    retval->resize(n);
    for (auto it = retval->begin(); it != retval->end(); ++it) {
        typename T::CPDDist cpd(rng, args...);
        *it = T(cpd);
    }
}
A: 

I think this would work:

template<typename T>
template<typename... Args>
void InitToRandomValues(vector<T>* retval, int n, RNG& rng, Args const&... args) {
    retval->resize(n);
    std::generate(retval->begin(), retval->end(), [] -> T() {
        typename T::CPDDist cpd(rng, args...);
        return T(cpd); });
}

It isn't much of a simplification though.

Alex - Aotea Studios
Yea, but it's probably the best that can be done though. I'll give the question another half hour and then mark this as best if nothing is better.
Neil G
Does this work in gcc 4.4, or do I need gcc 4.5?
Neil G
"error: expected primary-expression before '[' token"
Neil G
GCC4.5 adds lambda syntax. 4.4 doesn't have it.
greyfade
ah, okay thanks. Marking as correct.
Neil G