在向量上迭代时出界

Tob*_*son 1 c++ vector indexoutofboundsexception

我正在制作一个程序,将采用文本和:

  1. 计算找到一个单词的次数
  2. 将它们保存到结构中
  3. 打印出单词的次数.

但是当我尝试将字符串与结构字符串成员进行比较时,我遇到了问题.我得到的矢量超出了范围.请查看以下代码.希望有人能告诉我我做错了什么

#include <iostream>
#include<string>
#include <vector>

using namespace std;


struct word_entry {
  string word;
  int amount;
} ;

typedef vector<word_entry>  type_of_vector;

void insert(type_of_vector word_storage,string word_to_insert)
{
  bool word_found =false;

  for(int i = 0;i<=word_storage.size();i++)
    {
      if(word_storage.at(i).word==word_to_insert) //crashes the program
        {
          word_storage.at(i).amount++; 
           word_found=true;
        } 
    }    
}

int main()
 {
   type_of_vector word_vector;
   string word_to_insert="kalle";   
   word_entry insert_word={word_to_insert,1};  
   word_vector.insert(word_vector.end(),insert_word);   
   insert(word_vector,word_to_insert); 
 }
Run Code Online (Sandbox Code Playgroud)

Tob*_*obi 5

它一定要是

for(int i = 0; i < word_storage.size();i++)
Run Code Online (Sandbox Code Playgroud)

使用"小于"'<'而不是"小于或等于"'<='.

  • 更好的是,如果你要使用C++ 11,请使用基于范围的`for`:`for(word_entry&entry:word_storage)` (2认同)