Search code examples
c++vectorerase

Can someone explain why this vector erase operation isn't working properly?


    vector<int> nums{1,2,3,0,0,0};
    
    for(int i = 0; i< nums.size(); i++){
        if(nums[i] == 0){
            nums.erase(nums.begin() + i);
        }
    }
    for(int i = 0; i< nums.size(); i++){
        cout << nums[i] << " ";
    }
    //I keep getting [1, 2, 3, 0]

I want to remove the zeros from the vector so that I only have 1,2,3 left over. However, the method I'm using seems to keep leaving one zero at the end. I've been at it for a while and I've played with the indexing but I can't seem to get it to work correctly. I'd appreciate help thanks.


Solution

  • Every time you erase from a vector the index of following elements decreases by 1. You need to account for this:

    for(int i = 0; i< nums.size(); i++){
            if(nums[i] == 0){
                nums.erase(nums.begin() + i);
                --i; // <-- HERE
            }
        }
    

    This is an O(n^2) operation. You can do this in O(n) like this:

    nums.erase(std::remove(nums.begin(), nums.end(), 0),
               nums.end());