我有一个函数,一旦应用了一个QHash,直到一个给定位置的末尾,需要相应地更新相应的QList,以反映QHash的变化。为了快速查找,QHash将存储为QHash<QString(Train ID), int(position of train)>。QList将QList存储为指向对象的指针列表。此函数的给定标头为:QList<FreightCar*> splitTrain(int pos),不能更改(即只能像在标头中一样使用)。我得到的函数只删除给定的值"pos“,不使用迭代器的For循环通过QHash迭代。在QHash之后,QList被更新为QHash中的值,但不完全正确。
下面是该函数的实现。
QList<FreightCar*> FreightTrain::splitTrain(int pos)
{
QTextStream cout(stdout);
QHash<QString, int>::iterator i;
QList<FreightCar*>::iterator j;
int posI;
posI = pos;
//removal of posbyid by given id onwards
for(i = this->posByID.begin(); i != this->posByID.end(); )
{
if(i.value() == posI)
{
i = this->posByID.erase(i++);
posI++;
}
else
i++;
}
//end of removal of posbyid by given id onwards
//Display current values in QHash of posByID
for(auto i = this->posByID.begin(); i != this->posByID.end(); i++)
{
cout << "keyid: " << i.key() << " valpos: " << i.value() << endl;
};
//End of display of posByID values
//removal of same ID values from QHASH posbyId in QLIST physicalorder
bool yes;
for (auto j = this->physicalOrder.begin(); j != this->physicalOrder.end();)
{
yes = false;
for(auto i = this->posByID.begin(); i != this->posByID.end(); ++i)
{
if((*j)->getID() == i.key())
{
if(i.key() == pos)
{
yes = true;
break;
}else
{
yes = false;
break;
}
}else if((*j)->getID() != i.key())
{
yes = true;
}
}
if(yes == true)
{
j= this->physicalOrder.erase(j);
}else
{j++;};
}//end of removal of same ID values from posbyId in physicalorder
//display of QList after deletion.
for (auto j = this->physicalOrder.begin(); j != this->physicalOrder.end(); j++)
{
cout << (*j)->toString() << endl;
}
//end of display of list after deletion.
return *this;
};在我创建了几个对象(火车车厢)之后,程序的输出:

拆分函数需要将所有值/对象从给定位置移到末尾。因此,所有的价值,从开始到提供的立场,需要保持。
货运列车中的每一个物体(货车)都是按物理顺序创建的。每辆货车都有一个ID,一个指定的重量(吨位)和一个指定的类型(箱车,GONDOLACAR,油罐车,FLATBEDCAR)。"valpos“是指每辆车制造1、2、3、4、5等的顺序。"keyid“指的是实体订单QList中货车的ID。
发布于 2018-09-18 08:36:37
通过复制/粘贴通过QHash运行的初始循环使其工作,再次通过循环运行以删除以下值,因为QHash与QMap相同,因此值保存与数组不同,因此您可以循环通过某些值。
https://stackoverflow.com/questions/52362217
复制相似问题