I want to replace my buffer string from a value of "eof" to "\0".
I’m using std::replace to replace "eof" to "\0".
std::string buffer = "eof";
std::replace(buffer.begin(), buffer.end(), std::string("eof"), std::string("\0"));
Compiler :
no match for ‘operator==’ (operand types are ‘char’ and ‘const std::__cxx11::basic_string<char>’)
What am I doing wrong?
>Solution :
The problem is that internally std::replace checks == on *first and old_value where first is the first argument passed(iterator here) and old_value is the third argument passed shown in the below possible implementation:
template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value)
{
for (; first != last; ++first) {
//----------vvvvvv vvvvvvvvv--------->compares *first with old_value
if (*first == old_value) {
*first = new_value;
}
}
}
Now *first is char and old_value(and new_value) is std::string in our example and since there is no operator== for checking if a char and a std::string are equal and also as there is no implicit conversion between the two, we get the mentioned error.
One way to solve this is to use std::string::replace. More alternatives can be found at : Replace substring with another substring C++