c++ - 解决 std::replace 编译错误

标签 c++

我有下面的代码行

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/

相关文章:

c++ - 如何在 Linux 上调试 `SIGTERM`

c++ - 使用 C++ 的 Google Cloud 语音 API,第一步是什么?

c++ - QT : webkit webkitwidgets creating a click package on Ubuntu 中的未知模块

c++ - 如何基于函数参数C++更改对象属性

c# - 如何向 MFC 应用程序添加 list 并设置支持的操作系统?

c++ - 柏林噪声 2D : turning static into clouds

c++ - 左值引用对象 : Clang and gcc disagree 上的 Constexpr 成员函数

c++ - 值在常量表达式 C++ 中不可用

c++ - std::fabs() 优化不好?

c++ - 从哪里可以获得 Windows 7 的子身份验证包示例?