繁体   English   中英

C ++为什么“ deque迭代器不可取消”

[英]C++ why “deque iterator not dereferencable ”

我正在执行https://www.testdome.com/for-developers/solve-question/9930中提供的示例测试

“ TrainComposition是通过从左侧和右侧装卸货车来构建的。例如,如果我们先从左侧装货车7,然后再从左侧装货车13,我们得到两个货车的组合(从左到右依次是13和7。现在,第一个可以从右侧分离的旅行车是7,第一个可以从左侧分离的旅行车是13。实现对这个问题进行建模的TrainComposition。”

我通过使用std :: deque修改了代码,但是在构建它时,发生了一个错误:“ deque iterator not dereferencable”。 为什么会发生此错误,以及如何解决?

    #include <stdexcept>
#include <iostream>
#include <deque>

class TrainComposition
{
    //std::vector<int> wagons;

public:

    std::deque<int> wagons;

    void attachWagonFromLeft(int wagonId)
    {
        wagons.push_front(wagonId);
    }

    void attachWagonFromRight(int wagonId)
    {
        wagons.push_back(wagonId);
    }

    int detachWagonFromLeft()
    {
        std::deque<int>::iterator it = wagons.begin();
        wagons.pop_front();
        return *it;
    }

    int detachWagonFromRight()
    {
        std::deque<int>::iterator it = wagons.end()-1;
        wagons.pop_back();
        return *it;
    }
};

#ifndef RunTests
int main()
{
    TrainComposition tree;
    tree.attachWagonFromLeft(7);
    tree.attachWagonFromLeft(13);
    std::cout << tree.detachWagonFromRight() << "\n"; // 7 
    std::cout << tree.detachWagonFromLeft() << "\n"; // 13
    return 0;
}
#endif

detachWagonFromLeft()的以下指令序列是一个问题:

std::deque<int>::iterator it = wagons.begin();
wagons.pop_front();
return *it;

您将迭代器保存到第一个元素,但是pop_front()然后使该迭代器无效。 取消引用无效的迭代器是未定义的行为。

我建议这个更简单的版本可以工作:

int temp = wagons.front();
wagons.pop_front();
return temp;

您在detachWagonFromRight()函数中有一个类似的问题,可以修复为:

int temp = wagons.back();
wagons.pop_back();
return temp;

暂无
暂无

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

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