C++ Deque::swap() Function



The C++ std::deque::swap() function for deque container is used to exchange the contents of the deque. It swaps elements between two deques, ensuring both deques end up with the elements originally owned by the other. This operation is typically faster than manually copying the elements between containers.

The swap() function can be called in two ways: as a member function or as a non-member function. The time complexity of the swap() when used as member function is Constant i.e.O(1) orelse it is linear i.e.O(n) when used as non-member function. you can find the syntaxes of both the ways below.

Syntax

Following is the syntax for std::deque::swap() function.

void swap (deque& x);
or
void swap (deque<T,Alloc>& x, deque<T,Alloc>& y);

Parameters

  • x − It indicates the another deque container of the same type.
  • x, y − It indicates the deque containers of the same type.

x − Another deque object of same type.

Return value

This function does not return anything.

Exceptions

This function never throws exception.

Example

In the following example, we are going to consider the basic usage of swap() function.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C'};
    std::deque<char> b = {'X', 'Y', 'Z'};
    a.swap(b);
    std::cout << "After swapping:\n";
    std::cout << "a: ";
    for (auto& elem : a)
        std::cout << elem << " ";
    std::cout << "\nb: ";
    for (auto& elem : b)
        std::cout << elem << " ";
    std::cout << "\n";
    return 0;
}

Output

Output of the above code is as follows −

After swapping:
a: X Y Z 
b: A B C

Example

Consider the following example, where we are going to swap empty queue with non empty queue.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a;
    std::deque<int> b = {11,22,33,4};
    a.swap(b);
    std::cout << "After swap:" << std::endl;
    std::cout << "Size of 1st deque : " << a.size() << std::endl;
    std::cout << "Size of 2nd deque : " << b.size() << std::endl;
    return 0;
}

Output

Following is the output of the above code −

After swap:
Size of 1st deque : 4
Size of 2nd deque : 0

Example

Let's look at the following example, where we are going to use the swap to clear the deque.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C'};
    std::cout << "Before clearing:\n";
    std::cout << "Deque: ";
    for (auto& elem : a)
        std::cout << elem << " ";
    std::cout << "\n";
    std::deque<char>().swap(a);
    std::cout << "After clearing:\n";
    std::cout << "Deque: ";
    for (auto& elem : a)
        std::cout << elem << " ";
    std::cout << "\n";
    return 0;
}

Output

If we run the above code it will generate the following output −

Before clearing:
Deque: A B C 
After clearing:
Deque: 
deque.htm
Advertisements