栈是一种很常用的数据结构,根据栈的特点,我们当然可以自己写一个栈,但有时为了方便起见,我们可以使用STL中提供的栈容器<stack>,它提供了几种基本操作
stack::empty
bool empty ( ) const;
判断是否为空。
Return Value
true if the container size is 0, false otherwise.
<span style="font-size:24px;">// stack::empty
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
stack<int> mystack;
int sum (0);
for (int i=1;i<=10;i++) mystack.push(i);
while (!mystack.empty())
{
sum += mystack.top();
mystack.pop();
}
cout << "total: " << sum << endl;
return 0;
}</span>
Output:
total: 55
---------------------------------------------------------------------------------------------------------
stack::pop
void pop ( );
在栈的顶部移除元素。
// stack::push/pop
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
stack<int> mystack;
for (int i=0; i<5; ++i) mystack.push(i);
cout << "Popping out elements...";
while (!mystack.empty())
{
cout << " " << mystack.top();
mystack.pop();
}
cout << endl;
return 0;
}
Output:
Popping out elements... 4 3 2 1 0
---------------------------------------------------------------------------------------------------------
stack::push
void push ( const T& x );
在栈顶添加元素
// stack::push/pop
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
stack<int> mystack;
for (int i=0; i<5; ++i) mystack.push(i);
cout << "Popping out elements...";
while (!mystack.empty())
{
cout << " " << mystack.top();
mystack.pop();
}
cout << endl;
return 0;
}
Output:
Popping out elements... 4 3 2 1 0
---------------------------------------------------------------------------------------------------------
stack::size
size_type size ( ) const;
计算栈对象元素个数
// stack::size
#include <iostream>
#include <stack>
using namespace std;
int main ()
{
stack<int> myints;
cout << "0. size: " << (int) myints.size() << endl;
for (int i=0; i<5; i++) myints.push(i);
cout << "1. size: " << (int) myints.size() << endl;
myints.pop();
cout << "2. size: " << (int) myints.size() << endl;
return 0;
}
Output:
0. size: 0
1. size: 5
2. size: 4
---------------------------------------------------------------------------------------------------------
stack::top
value_type& top ( );
const value_type& top ( ) const;
返回栈顶元素
// test_stack.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stack>
#include <vector>
#include <deque>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
stack<int> mystack;
mystack.push(10);
mystack.push(20);
mystack.top()-=5;
cout << "mystack.top() is now " << mystack.top() << endl;
return 0;
}
Output:
mystack.top() is now 15
从中我们可以看出,栈并没有提供遍历的方法,唯一的方法就是将栈中的元素一个一个弹出来,但这样最后栈就改变了,所以在需要遍历的时候,我们要注意这个地方