在向量中存储字符串存在 SEG 错误
storing string in a vector has seg fault
我正在尝试从文件中读取单词并将它们存储到向量中,但索引不起作用。 让它不断出现赛格故障的原因是什么?为什么 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(( 在向量末尾分配新内存。查看吹链接以获取更多信息,在此处输入链接说明
相关文章:
- C++模板来检查友元函数的存在
- Seg Fault Issue C++ (file IO / getline)
- 既然存在危险,为什么项目要使用-I include开关
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- C++quit()函数中可能存在作用域问题
- C++擦除(如果存在)
- g++ 说函数不存在,即使包含正确的标头
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- C++Builder中的OnClick事件签名存在问题
- 如何正确地将分支添加到已存在的树中
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 如何检查QList中是否存在值
- Microsoft Visual Studio 2019交叉编译CMake库 - 有效,但存在SEG错误
- 由于相同的文件名/类名存在于不同的SO中而导致的SEG错误
- 在向量中存储字符串存在 SEG 错误
- Lamport 面包店算法的实现存在超过 1 个线程的 seg 错误