【问题标题】:Trying to access an index of an std::stack试图访问 std::stack 的索引
【发布时间】:2012-11-05 21:19:20
【问题描述】:
  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::stack 并发现“默认情况下,如果没有为特定堆栈类指定容器类,则使用标准容器类模板双端队列。”当我查看双端队列时,我发现它支持 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

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

【问题讨论】:

    标签: c++ stl stack operators std


    【解决方案1】:

    std::stack 不会从底层容器类型继承,而是将其调整为全新的接口。底层容器未暴露。这基本上就是适配器std::stackstd::queue 的意义所在:它们确保您使用的是更有限的接口,无论底层结构如何,该接口都是相同的。

    也就是说,您可以从std::stack 继承并从子类访问底层容器。它是一个名为cprotected 成员。

    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

    【讨论】:

    【解决方案2】:

    根据定义,堆栈不支持对其元素的随机访问。见std::stack reference

    实际上,在您的情况下,容器选择是错误的。如果您需要随机访问元素(不仅是顶部堆栈元素),请改用std::vector。相应的操作将是push_back() 将元素放在栈顶,pop_back() 从栈顶提取元素,back() 访问栈顶元素。

    【讨论】:

      【解决方案3】:

      您应该使用 .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);
      }
      

      【讨论】:

      • +1,我没注意到他没有尝试进入中间!
      猜你喜欢
      • 2017-08-28
      • 2012-09-11
      • 2021-02-07
      • 2012-01-17
      • 2019-11-22
      • 2021-11-05
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多