mercredi 3 juin 2015

For loops vs std::algorithms with an relatively old compiler

I know code is better when there are not any confusing for loops in it. And it is always good to reuse std::algorithms. But iterators and algorithm's syntax is really themselves looking confusing.

I want to give an real life example from my current project "vector<vector<QString>> in" and I want to copy its content to "vector<QVariant> out" I can't see the difference between

for (int i = 0; i <=in[0].size(); i++ ) 
{ 
    if(in[0][i].isNull() || in[0][i].isEmpty() ) 
        out[i] = "NONE";
    else
        out[i] = in[0][i];
}

and

std::transform(in[0].begin(), in[0].end(), out.begin(), [](const QString& a)->QVariant{
    if(a.isNull() || a.isEmpty() ) 
        return "NONE";
    else
        return a;
}); 

Since we have visual studio 2012 I even have to type the return value to my lambda. After using range like

in[0].map!( a => a.isNull() || a.isEmpty() ? "NONE" : a ).copy(out);

in D language I can't simply live with the transform code above. And I am even not sure if it is better than a basic for loop. My question is transform code above better than the for loop?

Aucun commentaire:

Enregistrer un commentaire