I have overloaded these operators to help me traverse a doubly linked list, but have run into a small bug, and being still new to c++ I am stuck. I never accounted for it the “amount” entered in would be a negative number. So I think I need to put a check in each operator for a negative number, because it will dramatically change the way I traverse the list, example, if im pointing at node 5 and I +(-3) I would want it to move backwards three nodes, the same with the -, 5 – (-3) would be go ahead three nodes. the logic seems easy, but the syntax is confusing. Here are the operators overloaded:
template <typename T>
typename doublyLinkedList<T>::iterator doublyLinkedList<T>::iterator::operator+(const int amount) const {
doublyLinkedList<T>::iterator tempClone(*this);
tempClone.pastBoundary=false;
T i;
for(i=0; i < amount; i++)
{
if(tempClone.current->forward == NULL)
{
tempClone.pastBoundary =true;
}else
{
++tempClone;
}
}
if(tempClone.pastBoundary == true)
{
return *this;
}else
{
return tempClone;
}
}
template <typename T>
typename doublyLinkedList<T>::iterator doublyLinkedList<T>::iterator::operator-(const int amount) const {
doublyLinkedList<T>::iterator tempClone(*this);
tempClone.pastBoundary=false;
T i;
for(i=0; i < amount; i++)
{
if(tempClone.current->backward == NULL)
{
tempClone.pastBoundary =true;
}else
{
--tempClone;
}
}
if(tempClone.pastBoundary == true)
{
return *this;
}else
{
return tempClone;
}
}
if(amount = (-amount))– unless amount is 0, this is always true.And it needs to go before the for-loop. In fact, I would probably do:
and vise versa for the other operator.