Home > other >  For Loop That Starts At Middle Of Range And Loops Around
For Loop That Starts At Middle Of Range And Loops Around

Time:11-04

Is it possible to have a for loop that starts at the middle of a range and then loops around to the beginning of the range and continues until it loops through the whole range? For example, assuming we have a range of 0 to 63, I want the loop to start at 22, continue looping until it reaches 63, then start at 0 and loop until it reaches 21. Is this possible with a for loop? Or would I require a while loop?

CodePudding user response:

I'd use two loop variables: one to count the number of repetitions and one to handle the desired index. Like this:

for (int i = 0, j = 22; i < 64;   i, j = (j   1) % 64)
    // do something with j

Of course, in real code you'd replace the magic numbers (22, 64) with something that more clearly reflects the actual objects involved.

CodePudding user response:

Yes, you can use a range-based for loop for this. A C 20 STL example (with using namespace std::ranges):

constexpr void foo(auto&& range) {
  auto middle = range.begin()   22;
  auto parts = {subrange{middle, range.end()}, subrange{range.begin(), middle}};
  for (auto&& elem: parts | views::join) bar(elem);
}

Maybe there's a better looking way / libary. With proper API, it should be something like

constexpr void foo(auto&& range) {
  for (auto&& elem: range | drop(22) | chain(range | take(22))) bar(elem);
}

CodePudding user response:

Yes, for example:

for( int i = 22, max = 63, end = i-1 ; i!=-1 ; i=i==end?-1:i==max?0:i 1 )
{
    // do something with i
}
  • Related