Search code examples
c++vectoriteratorstd

iterate an STL container not from the .begin()ing and wrap around


I have an std::vector, let's say of integers for simplicity.

std::vector<int> ivec;
ivec.push_back(1);
ivec.push_back(2);
... //omitting some push back's 3 to 99
ivec.push_back(100);

The standard way to iterate is known

std::map<int>::iterator it;
for( it = ivec.begin(); it != ivec.end(); it++ ) 
  print();

That iteration will print 1,2,3, ... 100.

I want to traverse all vector elements starting from a predefined index and not from it.begin(). I would like to print

3,4,5,6 ... 99, 100, 1, 2

Can you share your thoughts here?

It might ok to do it in two steps

for( it = ivec.begin()+index; it != ivec.end(); it++ ) and then (if index !=0)

for ( it = ivec.begin; it = it = ivec.begin() + (index-1); it++)

Solution

  • bool wrapped = false;
    for (auto it = vec.begin() + index; (it != vec.begin() + index) || !wrapped; ++it)
    {
        if (it == vec.end())
        {
            it = vec.begin();
            wrapped = true;
        }
        std::cout << *it;
    }