大家好,我刚开始学习C++,学习教材是C++ Primer 第五版。今天在完成书上的一个练习时(324页,练习9.43),总是发生out_of_range错误,经过调试发现,函数find_and_replace中的for循环没有终止。
代码如下:
#include <iostream>
#include <string>
int find_and_replace(std::string& org_str, const std::string& str4find, const std::string& str4replace);
int main(int argc, char const *argv[])
{
std::string str("I am a very loooooong string to be process!");
int find_times;
find_times = find_and_replace(str, "a", "###");
std::cout << find_times << std::endl;
std::cout << str << std::endl;
return 0;
}
int find_and_replace(std::string& org_str, const std::string& str4find, const std::string& str4replace)
{
int find_times = 0;
// 被检查字符串长度小于等于匹配字符串长度的情况
if (org_str.size() < str4find.size())
{
std::cout << "Error: The original string is too short!" << std::endl;
return find_times;
}
else if (org_str == str4find)
{
org_str.assign(str4replace);
++find_times;
return find_times;
}
// 其他情况
for (auto i = org_str.begin(), j = i + str4find.size(); j != org_str.end(); )
{
std::string temp(i, j);
std::cout << temp << std::endl;
if (temp == str4find)
{
j = org_str.erase(i, j);
org_str.insert(i, str4replace.begin(), str4replace.end());
std::cout << org_str << std::endl;
std::cout << *i << std::endl;
j = i + str4find.size();
std::cout << *j << std::endl;
++find_times;
}
else
{
++i;
++j;
}
}
// 跳出循环时,迭代器i和org_str.end()中间的字符串还没有检查
if (org_str.substr(org_str.size() - str4find.size()) == str4find)
{
org_str.erase(org_str.size() - str4find.size(), str4find.size());
org_str.insert(org_str.end(), str4replace.begin(), str4replace.end());
++find_times;
}
return find_times;
}
我在擦除和插入操作后都及时更新了迭代器j而且能够保证i始终在j之前,请问为什么我的循环终止条件j != org_str.end()没有起作用呢?
Since you know that the iterator is provided by the return value after erase, then insert may also invalidate the iterator, and there is a problem with the logic of your substitution method. If "a" is replaced with "abc", you This is infinitely replaceable. . .
If you change this string when traversing, it is likely that the iterator has expired. Check to see if this is the problem
Now that I understand this question, it is a self-question and answer. As the two friends above said, the problem lies in the fact that i and j are invalid iterators after erasing and inserting data, although std::cout outputs It looks correct, but it's essentially invalid. Since my compiler does not support
i = org_str.insert(i, str4replace.begin(), str4replace.end());
, I had to write a loop. The new version of the corrected code is as follows: