Ada*_*dam 0 c++ stl list vector
我正在尝试遍历一个字符串列表,并在所述字符串中找到给定字符所在的位置.然后,我根据字符出现的位置/字符将字符串存储在给定的向量中.在循环完成执行之前,我在以下代码中遇到运行时错误.我已经看过它六次了,似乎找不到任何错误.
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;
}
Run Code Online (Sandbox Code Playgroud)
更改
(str.size() + 1)
Run Code Online (Sandbox Code Playgroud)
...至
str.size()
Run Code Online (Sandbox Code Playgroud)
您将位于str.size()的未定义区域,更不用说PLUS了.
就此而言,你为什么要摆弄额外的char*而不是std :: string []?
对于THAT事,你为什么不干脆用的std :: string :: find()方法?
当然,假设您使用的是std :: string而不是其他字符串...... :)
实际上,回到调用站点... string :: find()返回目标字符匹配的索引,如果不匹配则返回string :: npos.那么,你能完全免除额外的功能吗?
int pos = (*ix).find( guess );
p.at( ( pos == string::npos ) ? 0 : ( pos + 1 ) ).push_back( *ix );
Run Code Online (Sandbox Code Playgroud)