替换字符串时出现编译错误
Getting compilation error while replacing a string
我创建了一个 Url 编码器类,其工作是编码或解码 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*"的转换无效 [-fallowive]
/usr/include/c++/4.6/bits/basic_string.tcc:214:5:错误:初始化参数 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&( [使用 _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;
}
好吧,解决方案中的错误是您尝试传递单个字符而不是std::string
或 c 样式的 0 终止字符串 ( const char *
( 来映射。
std::string::iterator
一次迭代一个字符,因此您可能需要使用 std::map< char, std::string >
。
it
是字符的迭代器(它的类型std::string::iterator
(。因此,*it
是一个角色。
你正在做reserved[*it]
,并且由于你给reserved
的类型(std::map<std::string, std::string>
(,下标运算符期望一个string
,而不是一个char
。
然后编译器尝试从char
到std::string
的用户定义转换,但是没有接受char
的string
构造函数。有一个接受char const*
(见这里(,但编译器无法将char
转换为char const*
;因此,错误。
另请注意,您不应该对 string::find()
返回的值使用 unsigned
,而应该使用 string::size_type
。
看起来 *it 的类型与什么不匹配
reservedChars.find()
应该接受。
尝试添加
const char* pit = *it;
就在之前
unsigned found = this->reservedChars.find(*pit);
if(found != string::npos){
encodeUrl.replace(position, 1, this->reserved[*pit]);
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?