2011-11-22 88 views
0

我试图通过一个字符串列表循环,并找到给定的字符在所述字符串中的位置。然后,我根据字符出现的位置/字符将字符串存储在给定的向量中。在循环结束执行之前,我在下面的代码中收到运行时错误。我已经查过了它六次,似乎无法找到任何错误。向量问题的向量

vector< vector<string> > p; 
for(list<string>::iterator ix = dictionary.begin(); ix != dictionary.end(); ix++) 
{ 
    int index = contains(*ix, guess); 
    index++; 

    p.at(index).push_back(*ix); //0 will contain all the words that do not contain the letter 
           //1 will be the words that start with the char 
           //2 will be the words that contain the the char as the second letter 
           //etc... 
} 



int contains(string str, char c) 
{ 
    char *a = (char *)str.c_str(); 
    for(int i = 0; i < (str.size() + 1); i++) 
    { 
     if(a[i] == c) 
      return i; 
    } 
    return -1; 
} 

回答

2

矢量<矢量>点p定义为空载体。在使用vector :: at()之前,必须添加向量元素。 例如:

const size_t MAX_LETTERS_IN_WORD = 30; 
vector< vector<string> > p(MAX_LETTERS_IN_WORD); 

/* same as before */ 

正如可以检查P.SIZE(替代),使用在()之前和的push_back()的附加元件为p根据需要

5

变化

(str.size() + 1) 

...到

str.size() 

你会在不确定的领土在str.size(),更不用说加一。

对于这个问题,为什么你摆弄额外的char *而不是std :: string []?

对于那个问题,你为什么不简单地使用std::string::find()

也就是说,是当然的,假设你使用的std :: string,而不是其他一些串... :)

事实上,早在调用点...字符串::发现()返回匹配目标字符的索引,或者如果不匹配,则返回string :: npos。那么,你可以完全免除额外的功能吗?

int pos = (*ix).find(guess); 
p.at(( pos == string::npos) ? 0 : (pos + 1)).push_back(*ix); 
+0

而且,正如其他人在这里所指出的那样,在尝试捅过它之前,您应该确实填充p。 – Christopher

2

与运行时错误的问题,可能是因为你在一个还不存在的位置访问矢量p。在访问特定索引之前,您必须在矢量中创建空间。