2012-11-17 27 views
3
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; 
} 
} 

我得到這些錯誤試圖訪問一個std ::指數堆棧

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 ::棧和發現「默認情況下,如果沒有爲特定的堆棧類指定容器類,則使用標準容器類模板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 

正如我所看到的,在std :: stack上使用operator []應該很好。有任何想法嗎?

回答

7

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

+0

從使用堆棧::℃;線我得到,錯誤:「堆」不是類或命名空間 –

+0

@TylerPfaff重新加載頁面,我更新了錯誤修正 – Potatoswatter

+0

這工作非常感謝,哪裏是一個很好的地方找到c + +參考? –

4

堆棧不支持通過定義它的元素進行隨機訪問。請參閱std::stack reference

其實在你的情況容器的選擇是錯誤的。如果您需要隨機訪問元素(不僅是頂層堆棧元素),而是使用std::vector。相應的操作將是push_back()將元素放置在堆棧頂部,pop_back()以從堆棧頂部提取元素並將back()用於訪問頂層堆棧元素。

6

您應該使用.top()方法來檢查堆棧頂部的內容,而不是索引。


因此,而不是您當前的代碼&hellip;

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); 
} 
+0

+1,我沒有注意到他沒有嘗試訪問中間! – Potatoswatter