C++ Queue Library - swap(queue) Function



Description

The C++ function std::queue::swap(queue) exchanges the contents of two queues.

Declaration

Following is the declaration for std::queue::swap(queue) function form std::queue header.

C++11

template <class T, class Container>
void swap (queue<T,Container>& q1, queue<T,Container>& q2) noexcept;

Parameters

  • q1 − First queue object.

  • q2 − Second queue object.

Return value

None

Exceptions

This member function never throws exception.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of std::queue::swap(queue) function.

#include <iostream>
#include <queue>

using namespace std;

int main(void) {
   queue<int> q1, q2;

   for (int i = 0; i < 5; ++i)
      q1.push(i + 1);

   for (int i = 0; i < 3; ++i)
      q2.push(i + 100);

   swap(q1, q2);

   cout << "Contents of q1 and q2 after swap operation" << endl;
   while (!q1.empty()) {
      cout << q1.front() << endl;
      q1.pop();
   }

   cout << endl << endl;

   while (!q2.empty()) {
      cout << q2.front() << endl;
      q2.pop();
   }

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Contents of q1 and q2 after swap operation
100
101
102
1
2
3
4
5
queue.htm
Advertisements