Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector insert() causes program to crash

This is the first part of a function I have that's causing my program to crash:

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 crashes right at the sorted part because I can see "here" on the screen but not "it failed." The following error message comes up:

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's causing the problem now, since I have a similar line of code elsewhere student.insert(student.begin() + position(temp, student), temp); that does not crash (where position returns an int and temp is another declaration of a struct Student). What can I do to resolve the problem, and how is the first insert different from the second one?

like image 831
wrongusername Avatar asked Mar 22 '26 14:03

wrongusername


2 Answers

It should be:

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

You were passing the iterator from the wrong instance.

like image 81
Matthew Flaschen Avatar answered Mar 25 '26 02:03

Matthew Flaschen


When you use std::vector::insert ( iterator position, const T& x );, the iterator position must point into that same vector. You're using an iterator from student with sorted.insert, which dies.

like image 37
Mike DeSimone Avatar answered Mar 25 '26 03:03

Mike DeSimone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!