问题描述
我有一个 std :: map< std :: string,foo>
,需要经常 find()
元素,而不是 std :: string
时,我有一个 const char *
。但是, map.find( key_value)
不起作用,我需要一个 std :: string
。因此,我需要 map.find(std :: string { key_value})
,但这将创建一个临时的 std :: string
(及其分配和取消分配),这可能会导致效率低下。这个推理正确吗?如果是,我该如何改善情况?
I have a std::map<std::string,foo>
and need to frequently find()
elements when instead of a std::string
, I have a const char*
. However, map.find("key_value")
won't work, I need a std::string
. So, I would need to map.find(std::string{"key_value"})
, but this will create a temporary std::string
(with its allocation and de-allocation) each time, making this potentially inefficient. Is this reasoning correct? If yes, how can I improve the situation?
我曾考虑过在 const char *
周围使用包装器,地图的键,它具有自己的比较功能,可以廉价地包装在任何 const char *
周围,无需分配。这是一个好主意吗? (请注意,我的映射值不可复制,只能移动)。
I was think about using a wrapper around const char*
as key for the map which has its own comparison function and can be cheaply wrapped around any const char*
, no need for allocations. Is this a good idea? (note that my mapped values are not copyable, only movable).
推荐答案
您可以使用以0终止的字符串来避免临时变量和地图的自定义比较器。
仍然,使用 unordered_map
可能会产生更好的索引性能。
You can avoid the temporaries by using 0-terminated strings and a custom comparator for the map.
Still, using an unordered_map
would likely yield better indexing performance.
另一个选择(更好)是使用包装程序,就像您想的那样。
实际上已经有 std :: reference_wrapper
An alternative (much better), is using a wrapper, just as you think.
There is actually already std::reference_wrapper
for that task.
仍然,优化的第一条规则是:不要这样做。
第二条规则:请不要
第三条规则(仅适用于专家):经过仔细测量和仔细考虑,您还是可以这样做。
Still, the first rule of optimisation: Do not do it.
The second rule: Do not do it.
The third rule (only for experts): After measurement and careful consideration, you might do it anyway.
唯一缺点是:您必须手动管理字符串的生存期。
The only downside is: You must manually manage the lifetimes of your strings.
如果您还是走这条路,并且在释放所有字符串之前不释放任何字符串,考虑使用您自己的自定义分配器。
If you are going down that road anyway, and you do not free any string until you free them all, consider using your own custom allocator.
这篇关于std :: string作为map键和map.find()的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!