stack swap() in C++ STL
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.
This function is used to swap the contents of one stack with another stack of same type and size.
Syntax :
stackname1.swap(stackname2) Parameters : The name of the stack with which the contents have to be swapped. Result : All the elements of the 2 stack are swapped.
Examples:
Input : mystack1 = {1, 2, 3, 4}
mystack2 = {3, 5, 7, 9}
mystack1.swap(mystack2);
Output : mystack1 = 9, 7, 5, 3
mystack2 = 4, 3, 2, 1
Input : mystack1 = {1, 3, 5, 7}
mystack2 = {2, 4, 6, 8}
mystack1.swap(mystack2);
Output : mystack1 = 8, 6, 4, 2
mystack2 = 7, 5, 3, 1
Note: In stack container, the elements are printed in reverse order because the top is printed first then moving on to other elements.
Errors and Exceptions
1. It throws an error if the stack are not of the same type.
2. It throws error if the stack are not of the same size.
2. It has a basic no exception throw guarantee otherwise.
// CPP program to illustrate // Implementation of swap() function #include <stack> #include <iostream> using namespace std; int main() { // stack container declaration stack<int> mystack1; stack<int> mystack2; // pushing elements into first stack mystack1.push(1); mystack1.push(2); mystack1.push(3); mystack1.push(4); // pushing elements into 2nd stack mystack2.push(3); mystack2.push(5); mystack2.push(7); mystack2.push(9); // using swap() function to swap elements of stacks mystack1.swap(mystack2); // printing the first stack cout<<"mystack1 = "; while (!mystack1.empty()) { cout<<mystack1.top()<<" "; mystack1.pop(); } // printing the second stack cout<<endl<<"mystack2 = "; while (!mystack2.empty()) { cout<<mystack2.top()<<" "; mystack2.pop(); } return 0; } |
Output:
mystack1 = 9 7 5 3 mystack2 = 4 3 2 1
Recommended Posts:
- Difference between std::swap and std::vector::swap
- Sort a stack using a temporary stack
- stack empty() and stack size() in C++ STL
- set::swap() in C++ STL
- map::at() and map::swap() in C++ STL
- swap() in C++
- priority_queue::swap() in C++ STL
- multiset::swap() in C++ STL
- forward_list::swap() in C++ STL
- unordered_map swap in C++ STL
- queue::swap() in C++ STL
- forward_list::swap() in C++ STL
- list::swap() in C++ STL
- unordered_multiset swap() in C++ STL
- unordered_set swap() in C++ STL
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.



