C++ Primer 習題9.35給出的答案如下: [cpp] #include<iostream> #include<cctype> #include<string> using namespace std; int main() {<span style="color:#ff0000;">string str = "This IS A Example"; </span> for(string::iterator iter = str.begin(); iter != str.end();++iter){ if(isupper(*iter)){ str.erase(iter); --iter; } } for(string::iterator iter = str.begin(); iter != str.end();++iter) cout<<*iter<<" "; return 0; } 以上運行報錯。 解: 由於第一個字母為T,--iter後 --iter--ite,,r則超出迭代范圍了。 改成string str = "this is A exaMple"; 如下,則可通過 [cpp] #include<iostream> #include<cctype> #include<string> using namespace std; 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; } } for(string::iterator iter = str.begin(); iter != str.end();++iter) cout<<*iter<<" "; return 0; }