Search code examples
c++vectorerase

vector erase() iterator outside range


I'm getting the error (vector erase() iterator out of range) on this line:

t[i].erase(t[i].begin()+k);

the input is:

4
9 2 7 8
6 4 3 7
5 8 1 8
7 6 9 4

The error pops up after i turns 2, it works for i=0,1 why?


#include <iostream>
#include <vector>
using namespace std;
int main(){
    int N, input;
    cin >> N;

    vector <vector <int>> t;
    int* a = new int [N];
    t.resize(N);

    for (int i = 0 ; i < N ; i++)
        for (int j = 0 ; j < N ; j++){
            cin >> input;
            t[i].push_back(input);
        }

    int minI = 0, minJ = 0;
    for (int i = 0 ; i < N ; i++){
        for (int j = 0 ; j < N ; j++){
            if (t[i][j] < t[minI][minJ]){
                minI = i;
                minJ = j;
            }
        }
        a [minI] = minJ;
        for (int k = 0 ; k < N ; k++)
            t[i].erase(t[i].begin() + k);
    }

    for (int i = 0 ; i < N ; i++)
        cout << a[i] << endl;

    delete [] a;
    system ("pause");
}

Heres a pic of input: enter image description here

and a pic of Error: enter image description here


Solution

  • As you erase elements of the vector, the vector gets smaller. Since your loop is going to N, eventually the loop index k gets larger than the remaining vector.