Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++)
like image 659
cateof Avatar asked Dec 16 '11 10:12

cateof


2 Answers

You can either:

  • develop an iterator class that wraps the vector::iterator and expose the behaviour you like (in particular: ++ checks for end() and replace it with begin() and adjust the other "border values")

  • fill the vector starting from 3 and wrap at 100, so that standard iteration will look as you want.

The choice depends on what else the vector is purposed and what else that iteration is needed.

like image 50
Emilio Garavaglia Avatar answered Nov 14 '22 04:11

Emilio Garavaglia


I'll assume that you already have a starting iterator. How you get this depends on whether you are using an indexable (vector) type or a forward iterator only, or a keyed type. Then you can do a loop something like this:

type::iterator start_iter = /* something from collection, perhaps begin()+index */
type::iterator cur_iter = start_iter;
do
{
  //do something with cur_iter

  ++cur_iter;
  if( cur_iter == collection.end() )
    cur_iter = collection.begin();
} while( cur_iter != start_iter );

That's the basic loop.

like image 27
edA-qa mort-ora-y Avatar answered Nov 14 '22 04:11

edA-qa mort-ora-y