【发布时间】:2018-05-29 21:11:15
【问题描述】:
以下代码示例将无法编译,但可以通过删除 std::string 之前的 const 说明符作为无序映射键来编译。
#include <unordered_map>
#include <utility>
#include <string>
#include <iostream>
int main()
{
int myint = 5;
std::unordered_map<const std::string, int*> map;
map.insert({"string", &myint});
std::cout << *map.at("string") << std::endl;
return 0;
}
为什么当const std::string 用作键时这段代码不编译,而std::string 有效?
【问题讨论】:
-
@NO_NAME 重复错误
-
这有什么意义?映射中的键是原始字符串的副本。
-
@Barmar 要明确吗?
-
我想知道为什么
map和unordered_map在这方面有所不同。很遗憾,副本似乎没有解决这个问题。 -
@NO_NAME 因为它没有回答提出的问题:为什么它不编译
标签: c++ unordered-map