2014-11-15 3 views
-1

Я понимаю, что этот вопрос задавали раньше, но ответы казались слишком определенными по отношению к кодексу.C++ std :: bad_alloc error with 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

Вы правы, спасибо. –

Смежные вопросы