I am trying to iterate over a range in one loop and NOT using below two for-loops:
if (firstIndex <= secondIndex)
for (int i = firstIndex; i <= secondIndex; i )
{...}
else
for (int i = firstIndex; i >= secondIndex; i--)
{...}
I considered using boost::irange but it does not cover secondIndex index.
Update: I need to preserve the order and CANNOT swap indices.
CodePudding user response:
In a contrived way, you can use
for (int i= first >= second ? first : second;
first >= second ? (i <= second) : (i >= first);
i = first >= last ? 1 : -1)
CodePudding user response:
Find out what is similar, and what is different; copy the former, abstract out the latter.
First we find out the direction, as the sign of the difference of indices. C does not have an integral sign function, but it is easy enough to calculate the sign by using the fact that true is 1
and false is 0
. We can use this sign value to step between the values (i.e. i
is equivalent to i = 1
, and i--
is i = -1
).
Now i <= secondIndex
and i >= secondIndex
can both be abstracted as i <= secondIndex * sign
, and i
and i--
as i = sign
.
int diff = lastIndex - firstIndex;
int sign = (diff > 0) - (diff < 0);
for (int i = firstIndex; i <= secondIndex * sign; i = sign) { ... }