【发布时间】:2019-11-18 07:52:34
【问题描述】:
我在将一个唯一指针插入std::unordered_map时停止了。
当我寻找答案时,我得到了一个链接:C++ inserting unique_ptr in map。
我试过了,但它对我不起作用。这是我到目前为止尝试的示例。
int main()
{
unordered_map<string,unique_ptr<char[]>> mymap;
string key = "ac";
char* ctr = "myvalue";
unique_ptr<char[]> value = make_unique<char[]>(100);
memcpy(value.get(), ctr,5);
mymap.insert_or_assign(key,std::move(value));
return 0;
}
遇到编译问题。
【问题讨论】:
-
你能发布你的编译错误吗?
-
您的地图键是整数但
key是字符串?请发布minimal reproducible example 并附上完整代码和错误消息 -
您是否有理由不使用
std::vector而不是std::unique_ptr<char[]>?或者,考虑到您的示例,std::string? -
在询问有关构建错误的问题时,请始终在问题本身中包含 full 和 complete 输出。并在出现错误的行上的minimal reproducible example 中添加 cmets。也请刷新how to ask good questions,以及this question checklist。
-
@MartinBonnersupportsMonica 是的,我添加它是因为问题说它正在使用
std::map,当它由于实际使用unordered_map而没有编译时我忘了删除它,并没有改变结果虽然
标签: c++ c++17 smart-pointers unique-ptr unordered-map