stack 模板类的定义在<stack>头文件中。
stack 模板类需要两个模板参数,一个是元素类型,一个容器类型,但只有元素类型是必要
的,在不指定容器类型时,默认的容器类型为deque。
定义stack 对象的示例代码如下:
stack<int> s1;
stack<string> s2;
stack 的基本操作有:
入栈,如例:s.push(x);
出栈,如例:s.pop();注意,出栈操作只是删除栈顶元素,并不返回该元素。
访问栈顶,如例:s.top()
判断栈空,如例:s.empty(),当栈空时,返回true。
stack 模板类需要两个模板参数,一个是元素类型,一个容器类型,但只有元素类型是必要
的,在不指定容器类型时,默认的容器类型为deque。
定义stack 对象的示例代码如下:
stack<int> s1;
stack<string> s2;
stack 的基本操作有:
入栈,如例:s.push(x);
出栈,如例:s.pop();注意,出栈操作只是删除栈顶元素,并不返回该元素。
访问栈顶,如例:s.top()
判断栈空,如例:s.empty(),当栈空时,返回true。
访问栈中的元素个数,如例:s.size()。
stack::empty
bool empty ( ) const;
判断是否为空。
Return Value
true if the container size is 0, false otherwise.
- // 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;
- }
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;
计算栈对象元素个数
|
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 |