我有以下代码
#include <iostream>
#include <string>
using namespace std;
string replace(string s){
for (int i=0;i<s.length();i++){
if (s[i]> 'b' && s[i]<'f'){
s.erase(s[i]);
}
}
return s;
}
int main(){
string s;
cin>>s;
cout<<replace(s)<<endl;
return 0;
}
如果我进入格鲁吉亚,它会向我显示例外情况“中止被称为”为什么?
答案 0 :(得分:6)
std::string::erase()
采用索引对或迭代器。
请看this link。
这里s[i]
给出了一个char,它被错误地转换为size_t
,因此,根据你的字符串,你基本上会尝试删除一个不存在的元素。
更清洁的解决方案是:
#include <string>
#include <iostream>
#include <cstdlib>
bool should_be_removed(char c) { return (c > 'b') && (c < 'f'); }
int main()
{
std::string s;
std::cin >> s;
s.erase(std::remove_if(s.begin(), s.end(), should_be_removed), s.end());
return EXIT_SUCCESS;
}