开发者

what is a wrong in this code?

i have following code

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

}

if i enter georgia i开发者_开发百科t show me exception "abort was called" why?


std::string::erase() takes either an index pair, or iterators.

Look at this link.

Here s[i] gives a char, which is mistakenly converted to a size_t so, depending on your string, you basically try to remove an element that doesn't exist.

A cleaner solution would be:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜