这段代码有什么问题?

dat*_*ili 1 c++ string

我有以下代码

#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;

}
Run Code Online (Sandbox Code Playgroud)

如果我进入格鲁吉亚,它会向我显示例外情况"中止被称为"为什么?

ere*_*eOn 6

std::string::erase() 采用索引对或迭代器.

看看这个链接.

这里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;
}
Run Code Online (Sandbox Code Playgroud)