STL栈的基本操作:
push(x) 将x加入栈中,即入栈操作
pop() 出栈操作(删除栈顶),只是出栈,没有返回值
top() 返回第一个元素(栈顶元素)
size() 返回栈中的元素个数
empty() 当栈为空时,返回 true
下面给出一个事例供参考
括号匹配程序:
#include<cstdio>
#include<stack>
using namespace std;
int main()
{
char str[100];
stack<char> s;
printf("输入序列:\n");
fgets(str,100,stdin);
int i = 0;
while(str[i] != 0)
{
if(str[i] == '(')
s.push('(');
else if(str[i] == ')')
{
if(s.empty())
{
printf("括号不匹配\n");
return 0;
}
else
{
char ch = s.top();
if(ch == '(')
s.pop();
else
{
printf("括号不匹配\n");
return 0;
}
}
}
i++;
}
printf("括号匹配\n");
return 0;
}