Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

What is a simpler/more readable alternative to this code structure?

$
0
0

There been many times lately where a C++ exercise has required me to do perform operations dependent on the relation between elements in a vector. For example to do x only if the next element in the vector is greater than the previous and do y otherwise.

I often solve these problems with the general code structure:

void foo(){    std::vector<int> v;    for (size_t i = 0; i < v.size(); ++i)    {        if (i < v.size() - 1)        {            if (v[i + 1] > v[i])    // some sort of condition            {                // execute compound statement x            }            else             {                // execute compound statement y            }        }        else         {            // execute compound statement y        }    }}

But it often becomes messy and hard to read when the compound statements x and y become large. Partially because I often have to create a function containing compound statement y to prevent having to copy all its code twice.
What is a more readable alternative to this structure?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>