tags:

views:

121

answers:

1

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 it show me exception "abort was called" why?

+6  A: 

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;
}
ereOn
Nice solution, but shouldn't `remove_if` be called `partition` or something since it doesn't actually remove anything nut just moves things about a bit. There's probably a really good reason for that name though.
Skizz
@Skizz: it doesn't necesarily moves the "removed" elements, it just moves the elements that don't match. The values of the elements after the iterator returned by `remove_if` are undefined.
ereOn
@ereOn: yes, you're right. I had to re-read the spec for `remove_if` carefully.
Skizz