1

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

2
  • What are you trying to do with that loop? Commented May 7, 2020 at 16:02
  • 2
    The advice given at the bottom of the error message is some of the best ever given in the history of the world. Commented May 7, 2020 at 16:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.