Search code examples
c++vectorerase

Why does my vector not re-size properly after erasing items?


I wrote a small program to remove 0's from a vector. But when I check, there is still a zero in the vector. why?

The size says its 4 when it should be 3 and there is still a zero showing.

int main()
{

    vector<int> nums1 = {1, 2, 3, 0, 0, 0};

    for(int i=0; i< nums1.size(); i++)
    {
        if(nums1[i] == 0)
            nums1.erase(nums1.begin() + i);
    }
    cout << "size is now: " << nums1.size() << endl;

    for(int j=0; j<nums1.size(); j++)
        cout<< nums1[j] << endl;
    return 0;
}

Solution

  • When an element of the vector is erased then all elements that follow it are moved left occupying the position of the erased element.

    That is if the element at the position i was erased then the element that follows it now will be at this position. So you shall not increase the position.

    For example

    for(  std::vector<int>::size_type i=0; i < nums1.size(); )
    {
        if(nums1[i] == 0)
            nums1.erase(nums1.begin() + i);
        else
            ++i;
    }
    

    Pay attention to that before the C++ 20 Standard you could use the standard algorithm std::remove like

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