gpt4 book ai didi

c++ - 这段代码有什么问题?

转载 作者:行者123 更新时间:2023-11-30 00:59:43 26 4
gpt4 key购买 nike

我有以下代码

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

}

如果我输入 georgia,它会显示异常“abort was called”,为什么?

最佳答案

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

this link .

此处 s[i] 给出了一个字符,它被错误地转换为 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;
}

关于c++ - 这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3871013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com