为什么map<string,string>接受整数作为值?
Why does map<string, string> accept ints as values?
我最近被这个震惊了:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
map<string, string> strings;
strings["key"] = 88; // surprisingly compiles
//map<string, string>::mapped_type s = 88; // doesn't compile as expected
cout << "Value under 'key': '" << strings["key"] << "'" << endl;
return 0;
}
它打印的"X"在ASCII中为88。
为什么字符串映射接受整数作为值?map operator[]
的文档说它返回mapped_type&
在这种情况下string&
,并且它没有从int
隐式转换,是吗?
这是因为,正如你所说,operator[]
返回一个std::string&
,它定义了一个operator= (char c)
。您注释掉的示例不调用赋值运算符,它是复制初始化,它将尝试调用类的显式构造函数,其中没有适用的构造函数std::string
.
要完成图片,请注意:
strings[88] = "key";
不编译,因为没有来自 char
/int
的std::string
构造函数。对于char
,std::string
只定义赋值运算符。
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 从 std::string 转换为 const 无符号整数
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 如何将带有前导零的整数插入到 std::string 中
- 为什么在添加整数时,STD :: String返回字符串的尾巴
- C++ 错误:对 '(std::string {aka std::basic_string}) (<char>无符号整数、字符)的调用不匹配
- 为什么map<string,string>接受整数作为值?
- 检查string是否是有效的整数或小数(正负两种情况)
- 在不使用外部库的情况下,在string中找到大整数的乘法,c++
- 将指针整数(int**)转换为c中的String
- 如何检查std::string是否确实是整数
- 如何从三个整数生成constexpr版本的字符串(或者可能是git/SVNcommit/rev.string)
- 矢量<string>以及映射<字符串,整数> 释放时可能失败? 想知道内存使用情况详细信息
- c++如何从字符数组(或std::string)解析整数(可能还有双精度)