“use algorithms; don’t write code” for multi-step logic?

Viewed 200

This question makes me think “don’t use an explicit loop at all! Use STL/Boost algorithms” but looking in detail, I note that there is an adjacent_difference, and accumulate and Boost has a zip somewhere,

while (i<l-1){
    ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
    i++;
}

They simply don’t stack together but each can only make a whole pass by itself. So using them in the straightforward way would require a number of intermediate copies containing partial results. That is, have adjacent_difference write a new vector which is the argument of zip, etc.

Now in “modern” C++ the mantra is that we should not be “writing code” and seldom need an explicit loop.

But my real-world experience is more like this case: the thing to be done is not a simple step and the results are not gathered in a batch like that.

So, how can this be written in a streamlined way, referring to operations to perform but not looping over the ranges and not pulling each element explicitly.

Boost iterator filters can in general build up more complex logic that ends up inside the driving loop (so no whole-thing-copy for intermediate results) but this example has several features illustrating what I find limiting with Boost range filters too! And setting it up is more complex than just writing the for loop!

So, if the C++ “who’s who” say that we should be able to write that way with new language and library features, how do you do that here, a simple case that’s more real-world than they show in their lectures?

2 Answers
Related