【发布时间】:2020-02-25 11:35:47
【问题描述】:
根据教授的要求,我目前正在 Cygwin 终端上使用 g++。
我应该接收一个输入文件并逐字阅读,然后将所有单词放入一个向量中,按字母顺序排序且没有重复。
但是,每次我尝试在某些循环内操作我的向量(即 - push_back)时,我的程序都会出现分段错误。
这是我的代码的 sn-p:
void word_count(ifstream& input){
string temp;
vector<string> v;
input >> temp; //set first variable
v.push_back(temp);
while (!input.eof()) { //I'm aware of the limitations while using !eof, this is just the way I am required to loop over a file
input >> temp;
for (vector<string>::iterator i = v.begin(); i != v.end(); i++) { //check entire vector for word
if (*i == temp) { //just break and skip the word if it already exists
break;
}
if (i == v.end() - 1) { //if the word doesn't exist yet
for (vector<string>::iterator k = v.begin(); k != v.end(); k++) { //re-search the vector for the proper place
if (k == v.end() - 1) { //if at the end, just push_back the vector
v.push_back(temp); //Causes segmentation fault
break;
}
if ((*k < temp) && (*(k + 1) > temp)) { //find correct place and insert the word in the vector
v.insert(k, temp); //Also causes segmentation fault if execution even manages to get this far
}
}
}
}
}
}
第 5 行的第一个 push_back 非常好,我可以多次复制和粘贴而不会出错。我也可以在输入>> temp(在while循环内部)之后立即push_back而不会出错。但是,如果我在“k”循环下尝试 push_back,则会出现分段错误。我完全被难住了。
我尝试在 StackOverflow 上查看其他与矢量相关的问题,但我真的不明白为什么我可以(或不能)在某些地方使用 push_back。
提前感谢您的帮助!
编辑 1:我应该提一下,我在 VS 2019 中对其进行了测试。弹出向量库文件,说明抛出了“读取访问违规”异常。没有分段错误(或者这可能是 VS 告诉我发生分段错误的方式?)
编辑 2:修改向量会使迭代器无效。不知道,谢谢大家的帮助!
编辑 3:我只能使用向量,不能使用集合或其他容器。如果我可以使用一套,我完全会。
【问题讨论】:
-
If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.这是来自push_back()方法的cppreference,可能这是你的问题 -
您是否允许/应该使用标准算法?如果是的话,这对我来说就像en.cppreference.com/w/cpp/algorithm/lower_bound 的工作
-
您应该永远在迭代向量时对其进行修改,正如@Raffallo 正确提到的那样(只是将其分解一下)。也许考虑使用
std::set来节省您的大量工作。它是有序的并且只包含唯一的元素。就好像它就是为这个任务而生的。 -
好吧,或者你一旦修改它就立即停止迭代 -
break一旦你插入。 -
我不知道 push_back 会使迭代器无效。谢谢你们!我将不得不仔细检查有关向量的文档。我没有使用
因为我需要使用 来“跳出框框思考”,正如我的教授所说的那样(尽管正如你所说, 非常适合这项任务)。