0

I have the code line below

std::string inStr = "I go, I walk, I climb";
std::replace( inStr.begin(), inStr.end(), "I", "you");//C2782

With the above code lines, I am getting the compile error

error C2782: 'void std::replace(_FwdIt,_FwdIt,const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous

What could be wrong with the in input parameters?

Niall
  • 30,036
  • 10
  • 99
  • 142
user987316
  • 894
  • 4
  • 13
  • 35

3 Answers3

4

I believe the error is because the type of "I" is const char[2] and the type of "you" is const char[4] and not the char* you may be expecting.

The array decays to the pointer when required, but the template type deduction doesn't do that automatically.

Bear in mind as well, that with std::replace you will want to replace individual elements in the original string, so only use char.


A simply alternative snippet of code to replace the "I" with "you" is;

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    std::string inStr = "I go, I walk, I climb";
    //std::replace( inStr.begin(), inStr.end(), "I", "you");

    auto at = inStr.find("I");
    while (at < inStr.size()) {
        inStr.replace(at, 1, "you");
        at = inStr.find("I");
    }
    cout << inStr << endl;
}

You can use the MS online compiler here to verify the code.

Niall
  • 30,036
  • 10
  • 99
  • 142
1

std::replace is used to replace the single element in the container with another element. For std::replace on std::string, you only can replace one char to another char in your string container.

Chen OT
  • 3,486
  • 2
  • 24
  • 46
  • This is correct as far as it goes, but algorithms are applied to **sequences**, which are more general than containers. Containers are one way of creating sequences, but not the only way. – Pete Becker Jan 27 '16 at 15:06
0

This will work for you, issue was because of size of "I" and "You" are different"

replace(inStr.begin(), inStr.end(), 'I', 'Y');

Try this,

size_t subStrinPos = -1;
do{
    subStrinPos = inStr.find('I', 0);
    if (subStrinPos != -1)
        inStr.replace(subStrinPos, strlen("I"), "You");
} while (subStrinPos != -1);
Akhil V Suku
  • 870
  • 2
  • 13
  • 34
  • 1
    `"I"` and `"You"` aren't `const char`. If they were, there would be no problem. – juanchopanza Jan 27 '16 at 07:25
  • 1
    `std::basic_string::find` does not return -1 it returns `std::basic_string::npos`. Just because `npos` is equal to -1 you should state your intent. Seeing `npos` will mean others who are looking at your code will instantly realise you are deliberately looking for the not found identifier and not a weird typo on your behalf. – graham.reeds Jan 27 '16 at 08:29