Last Updated : 23 Jul, 2025
In C++, stacks are a type of container adaptor with a LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we are going to discuss how to copy a stack in C++.
Copying a Stack to Another in C++To copy a std::stack, we can simply use the copy constructor or copy assignment operator of std::stack that takes another stack as a parameter and creates a new stack with the same elements.
Syntaxstack<type> myStack2(myStack1); // copy constructor myStack2 = myStack1 // copy assignment operatorC++ Program to Copy a Stack C++
// C++ program to illustrate how to copy a stack
#include <iostream>
#include <stack>
using namespace std;
int main()
{
// Declaring a stack of integers
stack<int> originalStack;
// Pushing integers into the original stack
originalStack.push(1);
originalStack.push(2);
originalStack.push(3);
// Copying the original stack to a new stack
stack<int> newStack = originalStack;
// Checking if the new stack is empty
if (newStack.empty()) {
cout << "New stack is empty." << endl;
}
else {
cout << "New stack is not empty." << endl;
}
return 0;
}
New stack is not empty.
Time complexity: O(N), where n is the number of elements in the stack.
Auxiliary space: O(N)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4