error: cannot convert 'std::basic_string

2019-03-25 10:05发布

问题:

I'm getting the following error:

error: cannot convert 'std::basic_string<char>::iterator {aka __gnu_cxx::__normal
_iterator<char*, std::basic_string<char> >}' to 'const char*' for argument '1' 
to 'int remove(const char*)'

For some reason, my program compiles perfectly when I'm working on a Mac... but once I use a Linux machine, this error pops up in more than one place. (If anyone could explain why this occurs, that would be great!)

Here's one of the instances where the error pops up:

SomeClass::SomeClass(string t, string art, Time dur) {
    char chars[] = ",";
    t.erase(std::remove(t.begin(), t.end(), chars[0]), t.end());
    art.erase(std::remove(art.begin(), art.end(), chars[0]), art.end());
    // Some more code ...
}

More specifically, the error is coming from this line:

t.erase(std::remove(t.begin(), t.end(), chars[0]), t.end());

Does anyone know how to approach this problem?

回答1:

You forgot to #include <algorithm>, where std::remove is located. Without that, your compiler only knows about this std::remove (I get the same error with Visual C++ 14), which is defined in indirectly included <cstdio> header.

Different behavior among compilers is a result of different #include hierarchies of the standard library implementations.