Search code examples
c++vectoriteratorstdvector

Looping back near the beggining using std::vector iterators


I have an iterator that needs to loop near the beginning of the vector whenever it reaches its end, for the amount it went over the end, like so:

std::vector<int> vec = {...}, vec1;
std::vector<int>::iterator it = vec.begin();

for(;vec.size() != 0;){

it += k; //k is a const integer
if(it >= vec.end()){
it -= items.end(); // something like that, but this syntax is obviously invalid
}

vec1.push_back(*it);
it = vec.erase(it);
}

So perhaps I increment vec{1,2,3,4,5} by 3, it should first remove 3, then 1 and put them in vec1, in a sense it loops around by however was left when it reached the end. I tried a bunch of different syntaxes, but there's always a type mismatch error. Is there an elegant way of doing this?


Solution

  • XY-solution: I recommend keeping an index instead of an iterator and use the remainder operator.

    for(std::size_t i = 0; vec.size() != 0;){
        i = (i + k) % vec.size();
        vec1.push_back(vec[i]);
        vec.erase(vec.begin() + i);
    }
    

    So perhaps I increment vec{1,2,3,4,5} by 3, it should first remove 3

    This doesn't match your attempted code. If you increment iterator to first element by 3 and erase it, then you'd be erasing the element with value 4.