Search code examples
c++vector

c++ How to remove any empty elements in a two dimension vector


I'm trying to remove any empty vectors inside another vector, below is my code:

#include<iostream>
#include<vector>

using namespace std;

int main()
{
    vector< vector<int> > vector(9);

    vector[0].push_back(2);
    vector[3].push_back(5);

    cout << vector.size() << endl; // print 9
    for (int i = 0; i < vector.size(); ++i) {
        if (vector[i].size() == 0) {
            vector.erase(vector.begin() + i);
        }
    }
    cout << vector.size() << endl; // prints 5?
}

Now, it prints 5 in the second print statement, because once I erase, the vector immediately updates its size. So now the size is different than before, and the index is not pointing to the correct element.

Is there anyway to fix this problem, so that I can find the correct size after removing all the empty elements? In this case, it should print 2?


Solution

  • You need to increment the index only if you didn't remove an element.

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