Vector insertion () crashes the program

This is the first part of the function that gives me an error:

vector<Student> sortGPA(vector<Student> student) {
    vector<Student> sorted;
    Student test = student[0];
    cout << "here\n";
    sorted.insert(student.begin(), student[0]);
    cout << "it failed.\n";
         ...

      

It falls right into the part sorted

because I see "here" on the screen, but not "it failed". The following error message appears:

Debug Assertion Failed!

(a long path here...)

Expression: vector emplace iterator outside range

For more information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

      

I'm not sure what is causing the problem now as I have a similar line of code elsewhere student.insert(student.begin() + position(temp, student), temp);

that does not crash (where position

int returns and temp

is another declaration of the Student structure) What can I do to solve the problem and how the first insert is different from the second?

+2


a source to share


2 answers


It should be:

sorted.insert(sorted.begin(), student[0]);

      



You were passing in an iterator from the wrong instance.

+8


a source


When you use std::vector::insert ( iterator position, const T& x );

, the iterator position

must point to the same vector. You are using an iterator from student

c sorted.insert

that dies.



+3


a source







All Articles