C++ Deque Library - swap() Function



Description

The C++ function std::deque::swap() exchanges the contents of the first deque with another. This function changes size of deque if necessary.

Declaration

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

C++98

template <class T, class Alloc>
void swap (deque<T,Alloc>& first, deque<T,Alloc>& second);

Parameters

  • first − First deque object.

  • second − Second deque 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::deque::swap() function.

#include <iostream>
#include <deque>

using namespace std;

int main(void) {

   deque<int> d1 = {1, 2, 3, 4, 5};
   deque<int> d2 = {50, 60, 70};

   cout << "Content of d1 before swap operation" << endl;
   for (int i = 0; i < d1.size(); ++i)
      cout << d1[i] << endl;

   cout << "Content of d2 before swap operation" << endl;
   for (int i = 0; i < d2.size(); ++i)
      cout << d2[i] << endl;

   cout << endl;

   swap(d1, d2);

   cout << "Content of d1 after swap operation" << endl;
   for (int i = 0; i < d1.size(); ++i)
      cout << d1[i] << endl;

   cout << "Content of d2 after swap operation" << endl;
   for (int i = 0; i < d2.size(); ++i)
      cout << d2[i] << endl;

   return 0;
}

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

Content of d1 before swap operation
1
2
3
4
5
Content of d2 before swap operation
50
60
70

Content of d1 after swap operation
50
60
70
Content of d2 after swap operation
1
2
3
4
5
deque.htm
Advertisements