user7054784
user7054784

Reputation: 51

Printing queue of queues elements

Hello I have the following function which prints the elements of a queue

 template<typename T>
 void queue<T>::print()
{
T x;
while(!empty())
{
    pop(x);
    cout<<x<<" ";
}

} I have made a queue of queues like this

 queue< queue<int> > my_queue_of_queues =queue< queue<int>>(); 

but how can I print all the elements of the queues of "my_queue_of_queues"?

Upvotes: 0

Views: 1046

Answers (2)

R Sahu
R Sahu

Reputation: 206607

but how can I print all the elements of the queues of "my_queue_of_queues"?

Option 1 Use operator<< instead of print.

template<typename T>
std::ostream& operator<<(std::ostream& out,  queue<T> const& q)
{
   // Don't modify the input.
   // Create a copy and modify the copy.
   queue<T> copy(q);
   while(!copy.empty())
   {
      T x;
      copy.pop(x);
      out << x << " ";
   }
   return out;
}

Option 2 Update print and call the operator<< function to re-direct the implementation.

template<typename T>
void queue<T>::print()
{
   cout << *this;
}

Option 3 Update print and call the operator<< function to re-direct the implementation but pass a std::ostream to print. Don't assume cout in print.

template<typename T>
void queue<T>::print(std::ostream& out)
{
   out << *this;
}

Upvotes: 2

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

If you don't want to change your print() implementation, simply define an operator<<(std::ostream&, const queue<T>&) overload and it will just work:

template <typename T>
auto& operator<<(std::ostream& os, const queue<T>& x)
{
    x.print();
    return os;
}

Upvotes: 1

Related Questions