Reputation: 25
I have a function that, once applied splits a QHash till the end from a given position and needs to update the accompanying QList accordingly to reflect the change of the QHash. The QHash stores as QHash<QString(Train ID), int(position of train)>
for quick lookup. The QList stores as QList as a list of pointers to objects. The given header for this function is: QList<FreightCar*> splitTrain(int pos)
and cannot be changed( i.e. can only use as is in header).
I've gotten the function to delete only given value "pos" and doesn't iterate thru the QHash with a For loop with the iterator. After the QHash the QList is updated to the values in the QHash, but not exactly.
Here is the implementation of the function.
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;
};
Output of program after I've created a few objects(train cars):
The split function needs to remove all values/objects from given position till the end. Thus all values from beginning till provided position needs to be kept.
Each object(Freight Car) in the freight train is created in physical order. Each freight car is given an ID an assigned weight(tonnage) and assigned Type(BOXCAR, GONDOLACAR, TANKCAR, FLATBEDCAR). "valpos" refers to the order in which each car was created 1,2,3,4,5 ect. "keyid" refers to the ID of the freight car in the physical order QList.
Upvotes: 0
Views: 474
Reputation: 25
Got it to work by copying / pasting the initial loop that runs thru the QHash to run thru the loop again to delete following values, as QHash is the same as QMap the values aren't saved same as an array thus you loop past certain values.
Upvotes: 0