【问题标题】:Vector insert() causes program to crash向量 insert() 导致程序崩溃
【发布时间】: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 传入的向量。

标签: c++ vector insert crash


【解决方案1】:

应该是:

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

您从错误的实例传递迭代器。

【讨论】:

    【解决方案2】:

    当您使用std::vector::insert ( iterator position, const T&amp; x ); 时,迭代器position 必须指向同一个向量。您正在使用来自 studentsorted.insert 的迭代器,它会死掉。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 2011-06-12
      • 2012-01-07
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多