【考点 · 6级】STL适配器容器 stack/queue —— 两个受限访问的容器,分别实现后进先出(LIFO)和先进先出(FIFO)。
stack(栈)只能操作栈顶:push 进、pop 出、top 看顶。queue(队列)只能操作队首和队尾:push 进队尾、pop 出队首、front 看队首。它们的底层默认都是 deque,但你不需要管底层,只管用接口就行。
⚠️ 易错:stack/queue 没有迭代器,不能用 for 遍历!想看内容只能逐个 pop。另外 empty() 判断空、size() 看大小,这些通用方法别忘了。
栈和队列的核心操作对比:
依次执行 push(1)、push(2)、push(3)、pop()、top(),栈顶元素是?
依次 push(A)、push(B)、push(C)、pop()、pop(),剩下什么?
() 的字符串,判断括号是否合法匹配。合法的定义:每个左括号都有对应的右括号,且嵌套正确。()()() → 合法 | (()) → 合法 | (() → 不合法#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
stack<char> st;
bool ok = true;
for (char c : s) {
if (c == '(') {
st.push(c); // 左括号入栈
} else {
if (st.empty()) { // 栈空说明没有匹配的左括号
ok = false; break;
}
st.pop(); // 匹配成功,弹出一个左括号
}
}
if (!st.empty()) ok = false; // 栈非空说明有未匹配的左括号
cout << (ok ? "合法" : "不合法") << endl;
return 0;
}
int x = st.pop() 是错的<stack>,queue 需要 <queue>