std::stack is a Container Adapter that provides a strict LIFO (Last-In, First-Out) interface on top of an underlying container (by default, std::deque).
#include <iostream>
#include <stack>
#include <string>
bool isBalanced(const std::string& expr) {
std::stack<char> s;
for (char ch : expr) {
if (ch == '(' || ch == '{' || ch == '[') {
s.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (s.empty()) return false;
char top = s.top();
s.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return s.empty();
}
int main() {
std::cout << std::boolalpha;
std::cout << "{[()]} is balanced: " << isBalanced("{[()]}") << "\n"; // true
std::cout << "{[(])} is balanced: " << isBalanced("{[(])}") << "\n"; // false
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Compare LIFO stack vs FIFO queue.
The default underlying container of std::stack.
Understanding the CPU's hardware call stack.