【问题标题】:program crashes when inserting new items to vector将新项目插入向量时程序崩溃
【发布时间】:2012-02-28 00:58:52
【问题描述】:
vector<Flight> flights;
while (!myReadFile.eof()) {
    flights.push_back(*(new Flight()));
// read some info...
}  

在第二个循环之后,程序崩溃并显示以下消息:

“cpi.exe 中 0x776315de 处未处理的异常:0xC0000005:访问冲突读取位置 0xfeeefee2。”

我该如何解决这个问题?

编辑:

vector<Flight> flights;
while (!myReadFile.eof()) {
    flights.push_back(Flight());
// read some info...
}

我试过这个,但仍然在第二个循环中崩溃

编辑:完整而

    int count = 0;
    myReadFile >> output;
    while (!myReadFile.eof()) {
        flights.push_back(Flight());
        flights[count].setFlightNum(atoi(output));

        myReadFile >> output;
        int x = atoi(output);
        flights[count].setStartX(x);
        myReadFile >> output;
        int y = atoi(output);
        flights[count].setStartY(y);

        count++;
        myReadFile >> output;
    }

【问题讨论】:

  • 你能告诉我们Flight的构造函数(默认和副本)吗?
  • 它是一个空的构造函数——所有的成员都是整数或浮点数。没有复制构造函数
  • 这是一个现场项目吗?只是对我们在天空中的朋友的友好关心。
  • 你能发布while循环的其余部分吗?
  • @user1027958:那么我真的怀疑它在将元素插入向量时是否崩溃,看起来崩溃是在while循环中的其他地方。

标签: c++ vector


【解决方案1】:

您应该直接流式传输到整数。如果您必须阅读“令牌”,则使用 std::string 但读入 char 数组总是很危险的。

您可能还应该拥有从流创建 Flight 对象的代码,尽管我不喜欢使用 std::istream&amp; operator&gt;&gt;(std::istream&amp;, Flight&amp; ),但我发现它“侵入性”且不可扩展。我更喜欢工厂。但是,无论如何,让我们编写该函数:

std::istream& operator>>(std::istream& is, Flight& flight )
{
    int flightnum, x, y;
    if( is >> flightnum >> x >> y )
    {
       flight.setFlightNum( flightnum );
       flight.setStartX( x );
       flight.setStartY( y );
    }
    return is;
}

现在:

std::vector< Flight > vec;

while( myReadFile )
{
    Flight flight;
    if( myReadFile >> flight )
       vec.push_back( flight );
}

【讨论】:

  • 几乎,您的代码允许静默读取半段飞行,而最后一次飞行则失败。 'while(myReadFile>>FlightNum>>StartX>>StartY) ...
  • 我不知道与我的代码有什么区别,但它现在可以工作了。谢谢
  • 是的,你可以这样做。我更喜欢在循环之外流入对象,但我可以使用 3 个整数并完成一个 if 测试。我可能会创建一个 Flight,但随后流式传输仍然会失败,并且不会添加到向量中。
  • 我已经修改了流式传输功能,以免触摸对象,除非它会成功。
【解决方案2】:

试试

vector<Flight> flights;
while (!myReadFile.eof()) {
  flights.push_back(Flight());
  // read some info...
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2017-09-05
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多