在向量中存储字符串存在 SEG 错误

storing string in a vector has seg fault

本文关键字:存在 SEG 错误 字符串 存储 向量      更新时间:2023-10-16

我正在尝试从文件中读取单词并将它们存储到向量中,但索引不起作用。 让它不断出现赛格故障的原因是什么?为什么 push_back(( 有效?使用索引和 push_back(( 之间的机制差异是什么?

vector<string> readWordToArray(string fileName, int wordCount){
vector<string> wordArray;
fstream inFile;
inFile.open(fileName);
string word;
int index = 0;
while(inFile >> word){
// doesnt work, need to change to wordArray.push_back(word);
wordArray[index] = word;   
index++;
}
return wordArray;
}

>wordArray[index]用于获取对向量中已经存在的元素的引用,我很确定使用超出范围的索引是未定义的行为。

要在末尾添加一个,您需要使用(如您在代码注释中指出的那样(:

wordArray.push_back(word);

你应该分配你的向量。 vector.resize(int n( 如果你想像数组一样对待。否则,您必须使用 Push_back(( 在向量末尾分配新内存。查看吹链接以获取更多信息,在此处输入链接说明