queue::swap() in C++ STL
Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed.
queue::swap()
swap() function is used to exchange the contents of two queues but the queues must be of same type, although sizes may differ.
Syntax:
queue1.swap(queue2)
OR
swap(queue1, queue2)
Parameters:
queue1 is the first queue object.
queue2 is the second queue object.
Return value: None
Examples:
Input : queue1 = {1, 2, 3, 4}
queue2 = {5, 6, 7, 8}
queue1.swap(queue2);
Output : queue1 = {5, 6, 7, 8}
queue2 = {1, 2, 3, 4}
Input : queue1 = {'a', 'b', 'c', 'd', 'e'}
queue2 = {'f', 'g', 'h', 'i'}
queue1.swap(queue2);
Output : queue1 = {'f', 'g', 'h', 'i'}
queue2 = {'a', 'b', 'c', 'd', 'e'}
Errors and Exceptions
1. It throws an error if the queues are not of the same type.
2. It has a basic no exception throw guarantee otherwise.
// CPP program to illustrate // Implementation of swap() function #include <bits/stdc++.h> using namespace std; int main() { // Take any two queues queue<char> queue1, queue2; int v = 96; for (int i = 0; i < 5; i++) { queue1.push(v + 1); v++; } for (int i = 0; i < 4; i++) { queue2.push(v + 1); v++; } // Swap elements of queues queue1.swap(queue2); // Print the first queue cout << "queue1 = "; while (!queue1.empty()) { cout << queue1.front() << " "; queue1.pop(); } // Print the second set cout << endl << "queue2 = "; while (!queue2.empty()) { cout << queue2.front() << " "; queue2.pop(); } return 0; } |
Output:
queue1 = f g h i queue2 = a b c d e
Time complexity: Linear i.e. O(n)
Recommended Posts:
- Find the Deepest Node in a Binary Tree Using Queue STL - SET 2
- Find the maximum cost path from the bottom-left corner to the top-right corner
- C++ program to compare two Strings using Operator Overloading
- not1 and not2 function templates in C++ STL with Examples
- Go vs C++
- Trie Data Structure using smart pointer and OOP in C++
- Modular Exponentiation of Complex Numbers
- std::hash class in C++ STL
- History of C++
- What are Forward declarations in C++
- __builtin_inf() functions of GCC compiler
- Structures in C++
- Variables in C++
- Implementing Forward Iterator in BST
- Count substrings that contain all vowels | SET 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnshumanSrivastava1



