2014-11-15 183 views
-1

我明白這個問題之前已被問過,但答案似乎太過指定的提問者的代碼。std :: bad_alloc錯誤與std :: vector

如果這被認爲是一個無用的重複問題,隨時刪除它或標記爲重複。

據我所知,我的代碼對於我正在嘗試實現的內容是正確的,它正在計算文本文件中指定單詞的出現次數。我將不勝感激任何幫助,謝謝。

的錯誤

This application has requested the Runtime to terminate it in an unusual way. 
Please contact the application's support team for more information. 
terminate called after throwing an instance of 'std::bad_alloc' 
    what(): std::bad_alloc 

我main.cpp中的部分(造成的問題)

//vectors to hold words from two files 
vector<string> wordlist; 
vector<string> file; 
vector<int> searchVec; 

//while a is not an empty string 
while (a != "") { 

    //getNextWord() returns each word in order from a text file 
    //a is a play script, b is a list of words to search for 
    a = infile.getNextWord(); 
    b = infile2.getNextWord(); 

    file.push_back(a); 

    //counts total words in play script 
    count++; 

    //increments and adds each word from the list of words to search for to the vector 
    for (int i = 0; b != ""; i++) { 

     wordlist.push_back(b); 

    } 

    //cycles through words to search for 
    for (int j = 0; j < wordlist.size(); j++) { 

     //cycle through te play script 
     for (int k = 0; k < file.size(); k++) { 

      //if the current play script word is the same as the test word, up the count 
      if (file[k] == wordlist[j]) { 

       searchCount++; 

      } 

     } 

     //print appropriate output, re-initialise the count to 0 for the next word 
     cout << "The word " << wordlist[j] << " occurs " << searchCount << " times." << endl; 

     searchCount = 0; 

    } 

} 
+0

你有沒有考慮過通過你的deb進行調試ugger? – Rapptz

回答

2

您如何看待這個循環終止?:

for (int i = 0; b != ""; i++) { 

    wordlist.push_back(b); 

} 
+0

對不起,這是錯誤的,我的函數getNextWord()實際上返回一個空字符串時,文件到達結束。 –

+0

'b'的值在循環內部沒有改變。所以這是一個無限循環。在這個循環內添加一個'cout'語句來確認。 – rockoder

+0

你是對的,謝謝。 –