最近在学习c++,在学习迭代器的过程中发现c++primer参考答案中,对于容器的迭代器的运算有一个错误:
比如说习题9.35:
习题9.35 使用迭代器寻找和删除string对象中所有的大写字符
primer给出答案为:
for(string::iterator ite = str.begin(); ite != str.end(); ite++){
if(isupper(*ite)){
ite = str.erase(ite);
ite--;
}
我在进行测试时,如果str字符串以小写字符开头,程序不会报错。但是,若果字符串的开头为大写字母的话,程序在运行时,就会出错。
我觉得主要原因是:
如果字符串的第一个字符就为大写,那么ite=str.erase(ite)此时是删除原先字符串的第一个字符后的字符串的begin()的迭代器,如果对它作ite--操作,就会导致运行错误
我的改正:
for(string::iterator ite = str.begin(); ite != str.end();){
if(isupper(*ite)){
ite = str.erase(ite);
}
else{
ite++;
}
}
希望理解的大神一起讨论。。。。