Search code examples
c++for-loopforeachiterationcycle

How would you iterate a vector?


This is my code:

std::vector<int> array;
array.push_back(1);
array.push_back(2);
array.push_back(3);
array.push_back(4);
array.push_back(5);

for (int i = 0; i < array.size(); i++) {
    if(array[i]==2 || array[i]==5) {
        array.erase(array.begin() + i);
        printf("### REMOVED ###\n", array[i], i);
    } 

    printf("inside val: %d | index: %d\n", array[i], i);
}

but as you can see, it outputs:

inside val: 1 | index: 0
### REMOVED ###
inside val: 3 | index: 1
inside val: 4 | index: 2
### REMOVED ###
inside val: 5 | index: 3

when my "expectation" is:

inside val: 1 | index: 0
### REMOVED ###
inside val: 2 | index: 1
inside val: 3 | index: 2
inside val: 4 | index: 3
### REMOVED ### 
inside val: 5 | index: 4

it "messes" with index/array's size during manipulation of itself, because will change memory pointer and size of the target.

My habit is to use a foreach statement and iterate a collection (C#/.Net), where even if I remove/add elements during the iteration, the next one is always the next from the beginning list.

How would you do it with C++?


Solution

  • The canonical form of a for loop that may remove elements is the following :

    for(auto i = begin(coll); i != end(coll);) {
    
        // ...
    
        if(hasToRemove)
            i = coll.erase(i);
        else
            ++i;
    }