C++ 括号检查功能仅测试输入的前2项?
我在实现这个函数时遇到了一点心理问题。它应该能够确保正确输入所有括号,例如:()[]为true,[({}[])]为true,但[[]为false。我必须在此函数中使用堆栈,但出于某种原因,它正确比较了2个括号,但输入2个括号以外的任何内容都不起作用。非常感谢您的帮助,谢谢 这是我的密码: 职能.h:C++ 括号检查功能仅测试输入的前2项?,c++,data-structures,stack,C++,Data Structures,Stack,我在实现这个函数时遇到了一点心理问题。它应该能够确保正确输入所有括号,例如:()[]为true,[({}[])]为true,但[[]为false。我必须在此函数中使用堆栈,但出于某种原因,它正确比较了2个括号,但输入2个括号以外的任何内容都不起作用。非常感谢您的帮助,谢谢 这是我的密码: 职能.h: #include<iostream> #include"stack.h" using std::string; bool bracketCheck(const string&
#include<iostream>
#include"stack.h"
using std::string;
bool bracketCheck(const string& s) {
Stack<char> stack;
if (!s.empty()) {
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
stack.push(s[i]);
}
else if (s[i] == ')' && stack.top() == '(' || s[i] == '}' && stack.top() == '(' || s[i] == ']' && stack.top() == '['){
stack.pop();
}
}
return stack.isEmpty() ? true : false;
}
}
#包括
#包括“stack.h”
使用std::string;
布尔括号检查(常量字符串和s){
堆叠;
如果(!s.empty()){
对于(int i=0;i
堆栈h:
template <typename T>
class Stack{
T* theStack_;
int max_;
int size_;
void grow(){
T* tmp=new T[max_*2];
for(int i=0;i<size_;i++){
tmp[i]=theStack_[i];
}
max_=max_*2;
delete [] theStack_;
theStack_=tmp;
}
public:
Stack(){
theStack_=new T[50];
max_=50;
size_=0;
}
void push (const T& data){
if(size_==max_){
grow();
}
theStack_[size_]=data;
size_++;
}
void pop(){
if(!isEmpty()){
size_--;
}
}
//removed top() const
T top() {
if(!isEmpty()){
return theStack_[size_-1];
}
return T{};
}
bool isEmpty(){
return size_==0;
}
~Stack(){
delete [] theStack_;
}
};
模板
类堆栈{
T*theStack_u2;;
int max_;
int-size_389;;
void grow(){
T*tmp=新的T[max_*2];
for(int i=0;i表达式;
if(括号检查(表达式))
你的问题就在这一行代码中:
if (s[i] == ')' && stack.top() == '(' || s[i] == '}' && stack.top() == '(' || s[i] == ']' && stack.top() == '[')
您需要像这样“分组”您的条件:
if ((s[i] == ')' && stack.top() == '(') || (s[i] == '}' && stack.top() == '{') || (s[i] == ']' && stack.top() == '['))
还请注意{
的排版修复。您的中相当长的布尔条件,否则如果需要一些“括号”:它自己的。混合使用&&
和| |
可能不是你认为的那样。在条件表达式中要具体,不要害怕在它们周围抛出括号。括号检查
的路径没有返回
语句。这意味着程序无效,编译器可以生成t做它想做的任何事。我把它改成上面的…但它仍然说())例如,是否平衡?这可能主要是一个问题吗?您是否仔细检查了您的代码?如果您在Visual Studio上,请使用F-10,看看您的代码与您的期望有何不同。似乎只要前两个括号满足条件,它就不会针对条件测试更多内容为什么pop()
是否不从数组中删除该字符?
if ((s[i] == ')' && stack.top() == '(') || (s[i] == '}' && stack.top() == '{') || (s[i] == ']' && stack.top() == '['))