C++ STL栈Stack的使用

C++ STL stack 用法

Stack(栈)是一种后进先出的数据结构,也就是LIFO(last in first out) ,最后加入栈的元素将最先被取出来,在栈的同一端进行数据的插入与取出,这一段叫做“栈顶”。

使用STL的stack,需要头文件#include<stack>

最常见,也是最简单的定义方式: stack <int> mystack; //构造一个用于存放int类型的空栈

栈的清空

	while (!s.empty())
	{
		cout << s.top() << "\n";
		s.pop();
	}

其他函数

s.push(10);入栈

s.pop();出栈

empty(); 堆栈为空则返回真

size(); 返回栈中元素数目

top(); 返回栈顶元素

代码实例

一道拆括号的练习题

#include<iostream>
#include<string>
#include<stack>
using namespace std;

int main()
{
	int total;
	cin >> total;

	stack<char> stackStr;
	string str;

	int j;
	for (j = 0; j < total; j++)
	{
		cin >> str;

		int i;
		while (!stackStr.empty())//清空栈
		{
			stackStr.pop();
		}

		for (i = 0; i < str.length(); i++)
		{
			if (str[i] == 'G')
			{
				cout << stackStr.size() << endl;
				break;
			}
			else
			{
				if (stackStr.size() == 0)//栈为空
				{
					stackStr.push(str[i]);//入栈
				}
				else if (stackStr.top() == '['&&str[i] == ']')//匹配
				{
					stackStr.pop();//出栈
				}
				else
				{
					stackStr.push(str[i]);//入栈
				}
			}
		}
	}
	cout << endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/89221898