Search code examples
stringc++11erase

Erase a specific character from a given string C++11


I would try to remove a specific character from a given string in the following code.

int main(void){
    string query="a*de*da";
    string org;
    uint8_t rmc='*';

    std::vector<string::const_iterator> wpos;
    for(string::const_iterator itr = org.begin();
        itr!=org.end();
        ++itr){
        if(*itr==rmc){
            wpos.push_back(itr);
        }
    }   

    uint64_t wcnt=0;
    for(auto witr: wpos){
         org.erase( witr-(wcnt++) );
    }   
    query=org;
    return 0;                                                                                                                                                                                                 
} 

In this code, I would expect that query="adeda" however, I got an error

 error: no matching function for call to ‘std::basic_string<char>::erase(__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >)’
org.erase(witr-wcnt);

My experimental setting is g++ 4.9.2 of devtoolset-3 on CentOS6.7


Solution

  • From C++98 to C++11, the signature of std::string::erase changed from

    iterator erase(iterator p)
    

    to

    iterator erase(const_iterator p)
    

    It seems like g++4.9.2 still uses the old version. Your example should compile if you change string::const_iterator to string::iterator.