【问题标题】:Getting compilation error while replacing a string替换字符串时出现编译错误
【发布时间】:2013-02-02 22:52:31
【问题描述】:

我创建了一个 Url Encoder 类,其工作是对 Url 进行编码或解码。

为了存储特殊字符,我使用了映射 std::map<std::string, std::string> reserved

我已经像这样初始化了地图this->reserved["!"] = ":)";

为了从给定字符串中读取字符,我使用了迭代器for(string::iterator it=input.begin(); it!=input.end(); ++it)

现在,当我尝试使用替换函数 encodeUrl.replace(position, 1, this->reserved[*it]); 替换特殊字符时

我收到以下错误

Url.cpp:在成员函数'std::string Url::Url::UrlEncode(std::string)'中:
Url.cpp:69:54:错误:从“char”到“const char*”的无效转换 [-fpermissive]
/usr/include/c++/4.6/bits/basic_string.tcc:214:5: 错误:初始化 'std::basic_string<_chart _traits _alloc>::basic_string(const _CharT*, const _Alloc&) 的参数 1 [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]' [-fpermissive]

我不确定代码有什么问题。这是我的功能

string Url::UrlEncode(string input){

    short position = 0;
    string encodeUrl = input;

    for(string::iterator it=input.begin(); it!=input.end(); ++it){

        unsigned found = this->reservedChars.find(*it);

        if(found != string::npos){

            encodeUrl.replace(position, 1, this->reserved[*it]);
        }

        position++;

    }

    return encodeUrl;
}

【问题讨论】:

    标签: c++ map stl


    【解决方案1】:

    it 是一个字符迭代器(它的类型为std::string::iterator)。因此,*it 是一个字符。

    您正在执行reserved[*it],并且由于您为reserved (std::map&lt;std::string, std::string&gt;) 指定的类型,下标运算符需要string,而不是char

    然后编译器尝试从charstd::string 的用户定义转换,但没有string 的构造函数接受char。虽然有一个接受char const*(参见here),但编译器无法将char 转换为char const*;因此,错误。

    还请注意,您不应将unsigned 用于string::find() 返回的值,而应使用string::size_type

    【讨论】:

      【解决方案2】:

      嗯,您的解决方案中的错误是您尝试将单个字符而不是 std::string 或 c 样式的 0 终止字符串 (const char *) 传递给映射。

      std::string::iterator 一次迭代一个字符,因此您可能需要使用std::map&lt; char, std::string &gt;

      【讨论】:

        【解决方案3】:

        看起来 *it 的类型和什么不匹配

         reservedChars.find() 
        

        应该接受。

        尝试添加

        const char* pit = *it;
        

        就在

        之前
        unsigned found = this->reservedChars.find(*pit);
        
            if(found != string::npos){
        
                encodeUrl.replace(position, 1, this->reserved[*pit]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-19
          • 2016-10-13
          • 1970-01-01
          • 2013-06-30
          • 2013-11-03
          • 1970-01-01
          相关资源
          最近更新 更多