ACM模版

stack(栈)和queue(队列)是在程序设计中经常会用到的数据容器,STL为我们提供了方便的stack(栈)和queue(队列)的实现。

准确的说,STL中的stack和queue不同于vector、list等容器,而是对这些容器进行了重新的包装。这里我们不去深入讨论STL的stack和queue的实现细节,而是来了解一些他们的基本使用。

stack

stack模版类的定义在<stack>头文件中。
stack模版类需要两个模版参数,一个是元素类型,另一个是容器类型,但是只有元素类型是必要的,在不指定容器类型时,默认容器的类型为deque。

定义stack对象的示例代码如下:

stack<int> s;
stack<string> ss;

stack的基本操作有:

s.push(x);  //  入栈
s.pop();    //  出栈
s.top();    //  访问栈顶
s.empty();  //  当栈空时,返回true
s.size();   //  访问栈中元素个数

Example:

/* * 1064--Parencoding(吉林大学OJ) * string和stack实现 */
#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int m;
        cin >> m;
        string str;
        int leftpa = 0;
        for (int j = 0; j < m; j++)
        {
            int p;
            cin >> p;
            for (int k = 0; k < p - leftpa; k++)
            {
                str += '(';
            }
            str += ')';
            leftpa = p;
        }
        stack<int> s;
        for (string::iterator it = str.begin(); it != str.end(); it++)
        {
            if (*it == '(')
            {
                s.push(1);
            }
            else
            {
                int p = s.top();
                s.pop();
                cout << p << " ";
                if (!s.empty())
                {
                    s.top() += p;
                }
            }
            cout << '\n';
        }
    }

    return 0;
}