【发布时间】:2010-05-01 04:59:53
【问题描述】:
这是导致程序崩溃的函数的第一部分:
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";
...
它在sorted 部分崩溃,因为我可以在屏幕上看到“这里”,但看不到“它失败了”。出现以下错误消息:
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.
我现在不确定是什么导致了这个问题,因为我在其他地方有类似的代码行 student.insert(student.begin() + position(temp, student), temp); 不会崩溃(其中 position 返回一个 int 和 temp 是结构学生的另一个声明) .我可以做些什么来解决这个问题,第一个插入与第二个有何不同?
【问题讨论】:
-
你真的应该通过引用将你的向量传递给函数......
-
@Mike DeSimone--但我不想改变向量,我只想得到一个改变的向量
-
@wrongusername:然后使用
const引用。您现在正在做的是(在调用函数时)创建向量的副本,然后将其传入。或者函数中是否有某些内容需要在本地更改学生向量? -
@Mike DeSimone——是的,我需要一个经过修改的向量副本。但是,如果我需要更改原始文件,那么更改向量的 void 函数与将函数设置为等于返回向量的更改副本的函数之间的区别是什么?
-
@wrongusername:我想你误解了我的意思。我认为您不希望该函数更改为
student传入的向量。但是我看到您的代码创建了另一个名为sorted的向量,并且假设您对其进行了更改而不是student,并以return sorted;结束了该函数。在这种情况下,student被读取但未更改,您可以将student指定为 const 引用,从而无需编译器复制作为student传入的向量。