C++中的stack類使用deque容器實(shí)現(xiàn),因此可以使用deque的拷貝構(gòu)造函數(shù)和賦值運(yùn)算符來完成棧的拷貝。
假設(shè)有一個(gè)名為mystack的stack對象,要將其拷貝為newstack對象,可以使用以下代碼:
#include <stack>
using namespace std;
int main() {
stack<int> mystack;
// 向mystack中添加元素
mystack.push(1);
mystack.push(2);
mystack.push(3);
// 使用拷貝構(gòu)造函數(shù)創(chuàng)建新的棧對象
stack<int> newstack(mystack);
// 打印newstack中的元素
while (!newstack.empty()) {
cout << newstack.top() << endl;
newstack.pop();
}
return 0;
}
在上述代碼中,使用stack<int>(mystack)
創(chuàng)建了一個(gè)名為newstack的新棧對象,并將mystack中的所有元素拷貝到新棧中。
需要注意的是,如果使用賦值運(yùn)算符mystack = newstack
,則會將新棧中的元素拷貝到舊棧中,而不是創(chuàng)建一個(gè)新的棧對象。因此,要?jiǎng)?chuàng)建一個(gè)新的棧對象,應(yīng)該使用拷貝構(gòu)造函數(shù)。