我正在尝试从字典文件中读取单词并且我在第4行读取文件中的段错误。从我所读到的关于c ++中的向量来使用insert命令我需要指定一个迭代器来用作占位符。要做到这一点,我在我的向量的开头实例化一个迭代器。
vector<string>::iterator it = dictionaryFile.begin();
在for循环中,我使用increment运算符
增加迭代器指向的位置it++;
我基于www.cplusplus.com上的示例。迭代器适用于前3行,然后发生段错误。我仔细检查了我的文件,以确保没有错误的字符被getline读入。我相信这个错误与我保留的调用有关,以确保矢量没有溢出。
由于我在声明时没有使用关键字new,因此向量限制为5的容量?我找不到任何使用新关键字的例子!
我已经包含导致此错误的代码段。请注意我已经多次重新设计了这个以试图解决这个段错误,这不是我原来的实现。我很感激c ++大师可能有的任何见解。谢谢你的时间。
vector<string> dictionaryFile (5, ""); //Declaration of vector that will hold the words in the dictionary
ifstream input; //Declaration of input file stream
input.open(inst.c_str());
/********************** Test to see if file was opened ********************************/
if(!input){
cerr << "The file " << inst <<" does not exists in this directory" << '\n';
}
/********************** File is successfully opened**********************************/
string temporaryProcessingString = ""; //This string will temporarily hold values read in from the file
vector<string>::iterator it = dictionaryFile.begin(); //Creates iterator to step through the vector and fix this wild shit
for(int i = 0; getline(input, temporaryProcessingString); i++){ //See I can follow directions given in class no eof used.
cout << "Does this print before SegFault 1 " << endl;
if(dictionaryFile.size() >= (dictionaryFile.capacity() - dictionaryFile.size()) ){ //If current size is greater the 50% capacity reserve size*2 more memory
int oldSize;
oldSize = dictionaryFile.size();
cout << "Does this print before SegFault 2 " << endl;
dictionaryFile.reserve(oldSize + oldSize); //Reservation new capacity for vector containing dictionary
}
/** this is a test bracket that solely keeps track of the vectors size and capacity in the terminal COMMENT OUT BEFORE SUBMITTING*/
cout << "________________________________________________" << '\n';
cout << "Loop Run: " << i << endl;
cout << "Size: " << dictionaryFile.size() << ", Capacity: " << dictionaryFile.capacity() << endl;
cout << "________________________________________________" << '\n';
dictionaryFile.insert(it, temporaryProcessingString); /*******************************THIS LINE CAUSES THE SEGFAULT! UNFORTUNATELY IT IS ALSO THE LINE THAT MOVES THE DATA INTO THE VECTOR************************/
it++;
cout << "Dictionary Entry: " << dictionaryFile[i] << endl;
}
cout << "Dictionary Entry Primary Test: " << dictionaryFile[0] << endl;
答案 0 :(得分:6)
当向量的大小接近其当前容量时(或者,在您调用vector::reserve
时,请参阅迭代器有效性here部分),内部算法将重新分配它并且可能将其移动到其他位置,使向量中的元素的所有迭代器都无效。
由于您的程序似乎只在最后插入,因此请使用vector::push_back
代替vector::insert
来阻止此操作。然后你也可以跳过reserve
- 内部算法非常好(你不必害怕为每个新元素重新分配的向量 - 算法比这更聪明)。