jeudi 5 avril 2018

Raw loops vs. algorithm for loops that depend on the index

I'm working on big codes for which performance matters. And one of the things I read is that raw loops should be avoided and replaced by for_each, range-based for loops, or STL algorithms etc etc. The problem is that in all (most) examples, everything looks adapted for the problem, i.e. for_each is shown with the cout routine *eye roll*.

In my case, the index inside the loop matters (unless you show me otherwise). For example, I want to create tables like this:

std::vector<double> vect1 (nmax), vect2 (nmax);
for (size_t i{0}; i < nmax; ++i) {
    vect1[i] = f(i);  // f is a routine defined somewhere else
    vect2[i] = f(i)+2.0;
}

What I could use is the generate function with a lambda function and it would be something like this:

std::vector<double> vect1 (nmax), vect2 (nmax);
size_t count{0};
generate(vect1.begin(), vect1.end(), [&]() {return f(count++);});

count=0;
generate(vect2.begin(), vect2.end(), [&]() {return f(count++) + 2.0;});

But I’m not a big fan of that, because:

  1. count exists until the end of the routine.

  2. We see that with another function, I have to put back count to zero and generate another vector again. I have to track down all the count variables etc. With the for loop, I could just put it in the same loop.

  3. With the for loop, the correspondence is seen easily. i is on the left and the right. With generate, I feel like it’s counting with a different variable on the left and the right, which means potential mistake.

  4. I can only do count++, not ++count, which means copy of variables.

Of course, this is a simple example. But I would like to know if the generate() version is still better for this kind of things (code/performance/readability wise). Or maybe there’s a better way of doing it, and I’m open to all suggestions and comments.

Thanks!

Aucun commentaire:

Enregistrer un commentaire