STL : stack 容器基本操作
stack 介绍
stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行元素的插入与提取操作。
stack是作为容器适配器被实现的,容器适配器即是对特定类封装作为其底层的容器,并提供一组特定的成员函数来访问其元素,将特定类作为其底层的,元素特定容器的尾部(即栈顶)被压入和弹出。
基本操作
- 构造函数
std::deque<int> mydeque (3,100); // deque with 3 elements
std::vector<int> myvector (2,200); // vector with 2 elements
std::stack<int> first; // empty stack
std::stack<int> second (mydeque); // stack initialized to copy of deque
std::stack<int,std::vector<int> > third; // empty stack using vector
std::stack<int,std::vector<int> > fourth (myvector);
- emplace()
在堆栈顶部的当前顶部元素上方添加一个新元素。这个新元素是在就地构造的。
std::stack<std::string> mystack;
mystack.emplace ("First sentence");
mystack.emplace ("Second sentence");
std::cout << "mystack contains:\n";
while (!mystack.empty())
{
std::cout << mystack.top() << '\n';
mystack.pop();
}
输出结果:
mystack contains:
Second sentence
First sentence
- top()
取得栈顶元素(但不删除)时间复杂度 :O(1)
std::stack<int> mystack;
mystack.push(10);
mystack.push(20);
mystack.top() -= 5;
std::cout << "mystack.top() is now " << mystack.top() << '\n';
return 0;
- empty()
检测栈内是否为空,若为空则返回真 时间复杂度 :O(1)
std::stack<int> mystack;
int sum (0);
for (int i=1;i<=10;i++) mystack.push(i);
while (!mystack.empty())
{
sum += mystack.top();
mystack.pop();
}
std::cout << "total: " << sum << '\n';
- push()
压栈 时间复杂度 :O(1)
std::stack<int> mystack;
for (int i=0; i<5; ++i)
{
mystack.push(i);
}
- pop()
移除栈顶元素 时间复杂度 :O(1)
while (!mystack.empty())
{
std::cout << ' ' << mystack.top();
mystack.pop();
}
- size()
返回stack内元素的个数 时间复杂度 :O(1)
std::stack<int> myints;
std::cout << "0. size: " << myints.size() << '\n'
- swap()
可以交换两个 stack 容器;
std::stack<int> foo,bar;
foo.push (10); foo.push(20); foo.push(30);
bar.push (111); bar.push(222);
foo.swap(bar);
std::cout << "size of foo: " << foo.size() << '\n';
std::cout << "size of bar: " << bar.size() << '\n';