Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

`std::replace` – Compiler deduces a char type from const char* literal converted explicitly to string

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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++

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading