我正在尝试遍历一个字符串列表,找出给定字符在所述字符串中的位置。然后,我根据字符出现的位置/情况将字符串存储在给定的向量中。在执行完循环之前,我在下面的代码中得到了一个运行时错误。我已经检查过它六次了,似乎没有发现任何问题。
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;
}发布于 2011-11-22 15:03:03
vector<向量>p将p定义为空向量。在使用vector::at()之前,必须向其添加向量元素。例如:
const size_t MAX_LETTERS_IN_WORD = 30;
vector< vector<string> > p(MAX_LETTERS_IN_WORD);
/* same as before */作为另一种选择,您可以在使用at()和push_back()之前先检查p.size(),根据需要将其他元素添加到p中
发布于 2011-11-22 14:51:37
变化
(str.size() + 1)...to
str.size()在str.size()中,您将处于未定义的领域,更不用说加1了。
就此而言,您为什么要摆弄额外的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 );发布于 2011-11-22 15:06:08
运行时错误的问题可能是因为您在一个尚不存在的位置访问向量p。在访问特定索引之前,必须在向量中留出空间。
https://stackoverflow.com/questions/8222995
复制相似问题