2

I have a vector of string constructed using:

vector<string> names;
names.push_back("Gates");
names.push_back("Jones");
names.push_back("Smith");
names.push_back("Gates");

I want to replace "Gates" with "Bill", for every occurrence of "Gates". For this the easiest solution I know is to use the replace function from algorithm and use it as:

replace(names.begin(), names.end(), "Gates", "Bill");

But I am getting following error:

 parameter type mismatch:incompatible types 'const char (&)[6]' and 'const char[5]'. 

I can solve it using implicit type casting like this:

replace(names.begin(), names.end(), "Gates", (const char (&)[6]) "Bill");

Can anyone explain what this error is, and better way to solve it or better way to do it. Or why do we need this type casting.

1
  • In C++17 you can do replace(names.begin(), names.end(), "Gates"s, "Bill"s) which looks a lot better. Commented Jun 20, 2017 at 23:02

2 Answers 2

5

The old/new value parameters in std::replace share the same type.

For example, the function might look like:

template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last, const T& old_value, const T& new_value);

Stolen from here, not that it's that significant.

"gates" is a const char[6] but bill is a const char[5], which is why you get the error about being unable to convert it.

You could either wrap each string literal in std::string() or just use the unary + operator to decay each literal to a const char*.

replace(names.begin(), names.end(), +"Gates", +"Bill"); //shorter
replace(names.begin(), names.end(), std::string("Gates"), std::string("Bill")); //clearer

I'm pretty sure ((const char (&)[6]) "Bill") violates strict aliasing, so I'd avoid casting between array types like that.

Sign up to request clarification or add additional context in comments.

Comments

2

I would suggest (assuming some using std;)

 replace(names.begin(), names.end(), string{"Gates"}, string{"Bill"});

since the type of "Gates" is char[6] (decayed to char*) and you want to replace std::string-s (not char* !!).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.