【发布时间】:2015-03-04 14:13:08
【问题描述】:
好吧,我知道人们一直在讨论这个话题,但我已经一个又一个问题地搜索并反复编辑我的代码,但我似乎仍然遇到这个问题。 这段代码基本上是为了运行一个向量并比较/组合它的内容。为此,我使用 'it' 和 'in' 遍历向量,并使用 .erase 删除已组合成向量新部分的内容。知道我基本上需要 .erase 函数和迭代器,我使用了 StackOverflow 上似乎在这种情况下工作的其他问题的一些代码(auto it 的东西)。由于我不熟悉该代码,因此我可能在这种情况下错误地使用了它,尽管我不确定。
无论如何,正如标题所示,我收到“向量迭代器不可递增”错误。在经历了第二个 for 循环几次后,该程序似乎遇到了这个错误。我已经尝试了很多东西,但我似乎无法弄清楚我的代码的哪一部分是真正的问题。
任何帮助将不胜感激!
\if (!strvector.empty()) {
for (auto in = strvector.begin(); in != strvector.end() - 1;) {//in order to process if there is more than one final piece
str = ' ' + *in + ' ';//adds spaces so it only compares beginnings & ends
if (strvector.size() < 2) {
break;
}//doesn't do anything if there are too few objects to process
for (auto it = strvector.begin(); it != strvector.end() - 1;) {
if (strvector.size() < 2) {
break;
}//doesn't continue if there are too few objects to process
str2 = ' ' + *it + ' '; //adds spaces so it only compares beginnings & ends
substr = str; //sets substring of string to be chopped up
while (substr.length() >= 6) { //only processes substrings >= 6 characters bc smaller bits are useless
size_t found = str2.find(substr); //searches str2 for substr
if (found != string::npos) {
str = str.substr(0, substr.length()) + ' '; //cuts substr off of str
str.append(str2); //adds str and str2
it = strvector.erase(it);
substr = 'a'; //shortens substr to get out of while
test=1;
}//end if
else {
substr.erase(substr.size() - 1, 1); //if substr was not found, decrement substr and compare again
}
}//end while
substr = str; //resets substr
while (substr.length() >= 6) { //only processes substrings >= 6 characters bc smaller bits are useless
size_t found = str2.find(substr); //searches str2 for substr
if (found != string::npos) {
str = str.substr(substr.length()) + ' '; //cuts substr from beginning of string
str = str2 + str; //adds str2 and str, with str2 at the beginning
it = strvector.erase(it++);
substr = 'a'; //shortens substr to get out of while
test=1;
}//end if
else {
substr.erase(0, 1); //erases the first character of the string
}
if (test < 1) {
it++; //increments if the erase function did not already do that
}
}//end while
if (test != 1) {
it++; //increments if the erase function did not already do that
}
if (test < 2) {
strvector.push_back(str); //adds new str to the vector
test = 0;
}
}//end ptr2 for
if (strvector.size() < 2) {
in = strvector.erase(in - 1);
}
else {
in++;
}
cout << "str1 is " << str << endl; //prints out str
}//end ptr for
}//end if vector is not empty
【问题讨论】:
-
it = strvector.erase(it++);只是看起来错了,没有分析它是否是错的。 -
你不能在遍历一个容器的同时修改它。
-
从
vector中删除一个条目会使下一次遍历的迭代器失效!