gpt4 book ai didi

c++ - 使用 const char* 作为 map/unordered_map 的键

转载 作者:太空狗 更新时间:2023-10-29 19:43:02 34 4
gpt4 key购买 nike

如何创建将使用 const char* 的 map/unordered_map直接作为 key ?

如果我使用 map<std::string,..> , 然后在每个解析 map["abc"] = ...一个新的std::string对象将被创建。这会导致分配内存、创建字符串对象并将字符串复制到其中的巨大开销。

如何声明使用 const char* 的 map 对象直接没有任何开销?

最佳答案

您可以使用 std::string_view :

std::map<std::string_view, int> Map;
Map["abc"] = 1; // no allocation necessary to store "abc"

它基本上是字符串对象的包装器。它是一个 View ,这意味着它不拥有字符串,因此不会复制和分配内存来存储字符串。

请注意,对于小字符串(以及文字),std::string 由于 SSO 而不会分配太多因此开销很小。始终在优化之前进行测量。

关于c++ - 使用 const char* 作为 map/unordered_map 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50608392/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com