我正在尝试遍历字符串列表并查找给定字符在所述字符串中的位置。然后我根据字符出现的位置/是否出现将字符串存储在给定的 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;
}
最佳答案
改变
(str.size() + 1)
...到
str.size()
你会在 str.size() 处处于未定义的领域,更不用说那个 PLUS 了。
就此而言,您为什么要摆弄额外的 char* 而不是 std::string[]?
对于那 问题,您为什么不简单地使用 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 );
关于c++ - vector 问题的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222995/