Receiving out of range error

I'm receiving this error
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 18446744073709551615) >= this->size() (which is 4)

after adding this code. It is supposed to remove the entered name from the student name vector and the corresponding grade from the student grades vector.

1
2
3
4
5
6
7
8
9
10
11
12
  else if(userSelection == 'r'){
         cout << "Which student would you like to remove" << endl;
         cin >> removedfirstName;
         cin >> removedlastName;
         removedName = removedfirstName + " " + removedlastName;
            for (i = 0; i < numStudents; ++i){
               if (studentNames.at(i) == removedName){
                  studentNames.erase(studentNames.begin()+i);
                  studentGrades.erase(studentGrades.begin()+i);
               }
            }
      }
The error is telling you that i is out of range.

Why are you using numStudents? You should be using studentNames.size().

One reason i could be out of range is that when you remove a student, you don't decrement numStudents. Since you don't exit the loop when you find a match, so i will index past the new end of the now shorter vector. This is why you should be using studentNames.size() which is automatically decremented when you delete a student. Why do duplicate housekeeping?

Topic archived. No new replies allowed.