试图访问一个std ::指数堆栈(Trying to access an index of an s

2019-07-03 21:43发布

  void PDA::parse(vector<string> words){
    for(int i=0; i<words.size();i++){//for each string in the input file
    string token=words[i];
    for(int j=0; j<token.length(); j++) //for each character in the string
      {
        char input=token[j];
        char matchingBracket=getMatchingBracket(input); //returns the matching bracket, should probably just have ( and [

        if(!stack[j]){//since j-1 when the index is 0 will cause an error
          if(stack[j-1]==matchingBracket){
            stack.pop();
          }else{
            stack.push(input);
          }

        }
  }
    accepted()?cout<<"The string "<<words[i]<<" is balanced and was accepted"<<endl : cout<<"The string "<<words[i]<<" is not balanced and was not accepted"<<endl;
}
}

我得到这些错误

PDA.cpp:25: error: no match for âoperator[]â in â((PDA*)this)->PDA::stack[j]â
PDA.cpp:26: error: no match for âoperator[]â in â((PDA*)this)->PDA::stack[(j - 1)]â

这些行

if(!stack[j]){//since j-1 when the index is 0 will cause an error
              if(stack[j-1]==matchingBracket){

我抬起头的std ::栈和发现,“默认情况下,如果一个特定的堆栈类指定容器类,标准容器类模板双端队列中。” 当我抬头双端队列我发现它支持运营商[]。 这是我宣布我的筹码。 在相应的头文件到该源文件。

#ifndef PDA_H
#define PDA_H
#include <stack>
#include <vector>
#include <deque>
class PDA{
 private:
  std::stack<char> stack;
 public:
  PDA();
  bool isEmpty();
  void parse(std::vector<std::string>);
  char getMatchingBracket(char);
  bool accepted();
};
#endif

在我看来,使用operator []上一个std ::栈应该只是罚款。 有任何想法吗?

Answer 1:

std::stack不会从底层容器类型继承,它它可以适应一个完全新的接口。 底层容器不会露出。 这是本质的适配器点std::stackstd::queue :他们确保您使用的是较为有限的接口,这将是一样的,不管底层结构。

这就是说,你可以继承std::stack和从子类访问底层的容器。 这是一个protected成员命名c

class my_stack : public std::stack< char > {
public:
    using std::stack<char>::c; // expose the container
};

int main() {
    my_stack blah;
    blah.push( 'a' );
    blah.push( 'b' );
    std::cout << blah.c[ 1 ]; 
}

http://ideone.com/2LHlC7



Answer 2:

您应该使用.top()方法来检查什么的堆栈,没有索引的顶部。


因此,而非目前的代码...

if(!stack[j]){//since j-1 when the index is 0 will cause an error
  if(stack[j-1]==matchingBracket){
    stack.pop();
  }else{
    stack.push(input);
  }
}

if(!stack.empty() && stack.top() == matchingBracket) {
    stack.pop();
} else {
    stack.push(input);
}


Answer 3:

堆栈不支持通过定义它的元素进行随机访问。 见的std ::栈参考 。

其实你的情况选择的容器是错误的。 如果你需要随机访问元素(不仅栈顶元素)使用std::vector来代替。 相应的操作将被push_back()上放置栈顶,元件pop_back()以提取从堆栈顶部元件和back()来访问栈顶元件。



文章来源: Trying to access an index of an std::stack