我有下面的代码行
std::string inStr = "I go, I walk, I climb";
std::replace( inStr.begin(), inStr.end(), "I", "you");//C2782
使用上面的代码行,我得到了编译错误
error C2782: 'void std::replace(_FwdIt,_FwdIt,const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous
in 输入参数可能有什么问题?
最佳答案
我相信错误是因为 "I"
的类型是 const char[2]
和 "的类型you"
是 const char[4]
而不是您可能期望的 char*
。
数组在需要时衰减为指针,但模板类型推导不会自动执行此操作。
请记住,std::replace
您将要替换原始字符串中的单个元素,因此只能使用char
。
将 “I”
替换为 “you”
的简单替代代码片段是;
#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;
}
您可以使用 MS online compiler here验证代码。
关于c++ - 解决 std::replace 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35030101/