c++primer 第四版 习题9.35
使用迭代器寻找和删除string对象中所有的大写字母
先出贴出配套习题解答上的答案;我在vs2019上编译不过去了
int main()
{
string str= "This Is A Example!";
for (string::iterator iter = str.begin(); iter != str.end(); ++iter)
{
if (isupper(*iter))
{
str.erase(iter);
--iter;
}
}
cout << endl << str;
return 0;
}
分析了一下,只要是string对象的首字母是大写就会报错,问题就出在这里,首字母是大写 就把迭代器往前移一位,在开始处移动一位不在string 迭代器范围内了,根本运行不到下面的 ++iter(如果能运行到这里,迭代器又回加回来,就没有问题了),不知道其他的编译器能不能通过。
我自己用while循环重写了一次,编译通过,下面是源程序
int main()
{
string str = "This Is A Example!";
string::iterator iter = str.begin();
while (iter != str.end())
{
if (isupper(*iter))
{
str.erase(iter);
continue;
}
++iter;
}
cout <<endl<< str;
return 0;
}

C++ Primer习题9.35解答与修正
本文探讨了C++ Primer第四版习题9.35的解答,该题要求使用迭代器从string对象中删除所有大写字母。原解答在VS2019上编译失败,问题出现在迭代器操作上。文章提供了修改后的代码,使用while循环代替for循环,成功解决了迭代器越界的问题。
401

被折叠的 条评论
为什么被折叠?



