试图访问std :: stack的索引

Tyl*_*aff 5 c++ stack stl std operators

  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;
}
}
Run Code Online (Sandbox Code Playgroud)

我收到这些错误

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)]â
Run Code Online (Sandbox Code Playgroud)

对于这些线

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

我查找了std :: stack并发现"默认情况下,如果没有为特定的堆栈类指定容器类,则使用标准容器类模板deque." 当我查找deque时,我发现它支持operator [].这是我宣布我的堆栈的方式.在此源文件的相应头文件中.

#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
Run Code Online (Sandbox Code Playgroud)

在我看来,在std :: stack上使用operator []应该可以正常工作.有任何想法吗?

Pot*_*ter 13

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 ]; 
}
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/2LHlC7


Che*_*Alf 6

您应该使用该.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);
  }
}
Run Code Online (Sandbox Code Playgroud)

if(!stack.empty() && stack.top() == matchingBracket) {
    stack.pop();
} else {
    stack.push(input);
}
Run Code Online (Sandbox Code Playgroud)