简体   繁体   English

Vector insert()导致程序崩溃

[英]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." 它在sorted部分崩溃,因为我可以在屏幕上看到“here”但不是“它失败了”。 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); 我不确定现在是什么导致了这个问题,因为我在其他地方有类似的代码行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). 不会崩溃(其中position返回int而temp是struct Student的另一个声明)。 What can I do to resolve the problem, and how is the first insert different from the second one? 我该怎么做才能解决问题,第一个插入与第二个插入有什么不同?

It should be: 它应该是:

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

You were passing the iterator from the wrong instance. 您从错误的实例传递迭代器。

When you use std::vector::insert ( iterator position, const T& x ); 当你使用std::vector::insert ( iterator position, const T& x ); , the iterator position must point into that same vector. ,迭代器position必须指向同一个向量。 You're using an iterator from student with sorted.insert , which dies. 你正在使用来自student一个迭代器sorted.insert ,它会死掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM