存储c ++链接列表向量中的指针

时间:2018-04-09 16:54:37

标签: c++

我想创建一些列表并存储指向向量中每个列表的指针。 我实现了,但我的问题是在某些功能中访问列表。 我有一个函数,它检查节点的链接顺序,并根据它们的顺序使某些列表无效。函数bool isValid()执行失效。

bool Train::isValid() const
{
    Car* curr;
    Car* temp;
    Car* Fin;
    Car* MVP;
    bool result;
    curr = m_head->getNext();
    while(curr != NULL)
    {
        temp = curr->getNext();
        Fin = temp->getNext();
        MVP = Fin->getNext();
        if((curr->getCargo()==3)&&(temp->getCargo()==2)||(curr->getCargo()==2)&&(temp->getCargo()==3))
            result = false;
        else if((curr->getCargo()==3)&&(temp->getCargo()==3)&&(Fin->getCargo()==3))
            result = false;
        else if((curr->getCargo()==0)&&(temp->getCargo()==0)&&(Fin->getCargo()==0)&&(MVP->getCargo()==0)&&((Fin->getNext())->getCargo()==0))
            result = false;
        else if((curr->getCargo()==4)&&(temp->getCargo()==0)&&(Fin->getCargo()==4))
            result = false;
        else
            result = true;
        curr = curr->getNext();
    }
    return result;
}

下面的代码部分是我访问矢量元素的地方。

for(unsigned int i = 0; i<Vec.size();i++)
    {
        cout<<i+1<<": "<<*Vec.at(i)<<endl;
    }
    typ = Vec.at((A/1111)-1)->Stringconverter(REMOVE);
    Vec.at((A/1111)-1)->removeCar((CARGO_TYPE)typ);
    for(unsigned int i = 0; i<Vec.size();i++)
    {
        bool N = Vec.at(i)->isValid();
            if(N)
        cout<<i+1<<": "<<*Vec.at(i)<<"(valid)"<<endl;
        else
            cout<<i+1<<": "<<*Vec.at(i)<<"(invalid)"<<endl;
    }

我正在使用函数的部分isValid()

2 个答案:

答案 0 :(得分:0)

您的代码肯定存在错误:

while(curr != NULL)   // NULL!! (the language supports nullptr)
{
    temp = curr->getNext();

    // Do not check `temp` is not nullptr before calling getNext()
    Fin = temp->getNext();

    // Do not check `Fin` is not nullptr before calling getNext()
    MVP = Fin->getNext();

    // Again in all the following (you don't check temp of Fin is not nullptr.
    if((curr->getCargo()==3)&&(temp->getCargo()==2)||(curr->getCargo()==2)&&(temp->getCargo()==3))
        result = false;
    else if((curr->getCargo()==3)&&(temp->getCargo()==3)&&(Fin->getCargo()==3))
        result = false;
    else if((curr->getCargo()==0)&&(temp->getCargo()==0)&&(Fin->getCargo()==0)&&(MVP->getCargo()==0)&&((Fin->getNext())->getCargo()==0))
        result = false;
    else if((curr->getCargo()==4)&&(temp->getCargo()==0)&&(Fin->getCargo()==4))
        result = false;
    else
        result = true;
    curr = curr->getNext();
}

// The result is just the value from the last iteration of the above
// loop. The last iteration of the above loop curr is valid but
// curr->getNext() returns nullptr so temp is nullptr.
// Thus the call temp->getNext() has undefined value.
// So the value of result is completely unknowable.
return result;

答案 1 :(得分:0)

感谢您的见解,真的很有帮助。 这是新的功能代码

Transactions