C++ Stack 库 - operator= 函数
描述
C++ 函数 std::stack::operator= 通过替换旧内容将新内容分配给堆栈。 如果需要,此方法会修改堆栈的大小。
声明
以下是 std::stack::operator= 函数形式 std::stack 头的声明。
C++11
stack<T, Container>& operator=( stack<T,Container>&& other );
参数
x − 另一个相同类型的堆栈对象。
返回值
返回 this 指针。
异常
此成员函数从不抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::stack::operator= 函数的用法。
#include <iostream>
#include <stack>
using namespace std;
int main(void) {
stack<int> s1;
stack<int> s2;
for (int i = 0; i < 5; ++i)
s1.push(i + 1);
cout << "Size of stack s1 before move operation = " << s1.size() << endl;
s2 = move(s1);
cout << "Size of stack s1 after move operation = " << s1.size() << endl;
cout << "Contents of stack s2" << endl;
while (!s2.empty()) {
cout << s2.top() << endl;
s2.pop();
}
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Size of stack s1 before move operation = 5 Size of stack s1 after move operation = 0 Contents of stack s2 5 4 3 2 1

