Reputation: 273
I have a small problem with defining my operator:
The code for the operator is:
ostream& operator<< (ostream& outs, const IntQueue& queue)
{
NodePtr temp = queue.head;
while(temp->link != NULL)
{
outs << temp->data;
outs << " ";
}
outs << endl;
return outs;
}
I want the operator to display temp->data for all nodes in the queue and also the last node(which points to NULL). I don't know how I can modify the while loop so it also writes out the last item (that points to NULL).
Hope I made myself clear.
Cheers.
Upvotes: 0
Views: 117
Reputation: 502
A few things to correct :
As pointed out in the comments, inside the while loop make sure to advance the pointer with something like
temp = temp->link;
Edit your loop to be a do-while loop. In that way you're sure that it'll print out even the last node.
Finally, as an additional point, you could consider overloading the '<<' operator for the Node object itself. That way your code to print out the entire queue would just be for iterating over the queue as shown below :
ostream& operator<< (ostream& outs, const IntQueue& queue)
{
Node* temp = queue.head;
if(NULL != temp) {
do
{
outs << temp;
temp = temp->link;
}
while(temp->link != NULL);
}
return outs;
}
Upvotes: 0
Reputation: 5118
Try the following:
ostream& operator<< (ostream& outs, const IntQueue& queue)
{
NodePtr temp = queue.head;
while(temp != NULL)
{
outs << temp->data;
outs << " ";
temp = temp->link;
}
outs << endl;
return outs;
}
Upvotes: 0
Reputation: 310990
ostream& operator <<( ostream& outs, const IntQueue& queue )
{
for ( NodePtr temp = queue.head; temp; temp = temp->link )
{
outs << temp->data;
outs << " ";
}
outs << endl;
return outs;
}
Upvotes: 3
Reputation: 534
You could try to use a do-while loop so that it wouldn't check for the NULL until after it had done the operation the last time.
I would imagine this would allow you to print out NULL as the final value.
Upvotes: 0