user173342
user173342

Reputation: 1840

Iterate over full array starting at any position, using only one variable

Fairly simple, I want to loop over every index of an array of arraysize using only one var for the loop. I have a way to do it with two vars i and j, where i tracks the actual index and loops around and j counts up to arraysize and terminates the loop:

for (unsigned int i = start, j = 0; //start is the starting index
 j < arraysize;
 ++i == arraysize ? i = 0 : 0, ++j)
{
 //do stuff
}

Is there some nifty way to do this with only i? Order doesn't matter, if backward iteration makes sense for some reason.

Clarification: I want to loop from start to arraysize - 1, then from 0 to start - 1.

Upvotes: 3

Views: 1358

Answers (6)

Jerry Coffin
Jerry Coffin

Reputation: 490538

At least as I understand it, you want to loop through the entire array, but you want to start from somewhere other than the beginning, then when you reach the end, you want to start back at the beginning and keep going until you reach the original starting point.

Assuming that's correct, it's pretty easy:

for (size_t i=0; i<arraysize; i++)
    process(array[(i+start)%arraysize]);

Upvotes: 7

Evgeny Panasyuk
Evgeny Panasyuk

Reputation: 9199

I would prefer to abstract that algorithm into generic function (which would work even on things like std::forward_list), without doing superfluous modulo and addition operations (though, they may be acceptable in many cases):

#include <algorithm>
#include <iostream>
#include <iterator>

template<typename FwdIter, typename F>
F for_each_shifted(FwdIter first, FwdIter start, FwdIter last, F f)
{
    using std::for_each;
    return for_each(first, start, for_each(start, last, f));
}

int main()
{
    using namespace std;
    int v[] = { 1, 1, 2, 6, 24 };
    for_each_shifted(begin(v), begin(v) + 3, end(v), [](int x)
    {
        cout << x << endl;
    });
}

Output is:

6
24
1
1
2

Live Demo

Upvotes: 5

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

For example you can use the folloing loop statement

for ( int i = start; i < arraysize + start; i++ )

and inside the loop body instead of i use expression i % arraysize

Upvotes: 0

mattnewport
mattnewport

Reputation: 14067

for (size_t i = start; (i + 1) % arraysize != start: i = (i + 1) % arraysize)  { 
    // stuff
}

Upvotes: 1

Zac Howland
Zac Howland

Reputation: 15870

This would get you there:

for (unsigned int i = start; i < start + arraySize; i++)
{
    DoSomething(array[i % arraySize]);
}

Alternatively:

for (unsigned int i = 0; i < arraySize;  i++)
{
    DoSomething(array[(i + start) % arraySize]);
}

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49896

for ( i=start; i<start+arraysize; i++ ) {
    // do stuff with (i % arraysize) in place of i
}

Upvotes: 1

Related Questions