使用const char *作为map/unordered_map的键 [英] Using const char* as key for map/unordered_map

查看:279
本文介绍了使用const char *作为map/unordered_map的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建将直接使用const char*作为键的地图/无序地图?

How to create map/unordered_map that will use const char* as key directly?

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

If I use map<std::string,..>, then on each resolving map["abc"] = ... a new std::string object will be created. That causes a big overhead for allocating memory, creating a string object and copying the string into it.

如何声明一个直接使用const char*且没有任何开销的地图对象?

How do I declare a map object that uses const char* directly without any overhead?

推荐答案

您可以使用 std::string_view :

You can use a std::string_view:

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

基本上,它是字符串对象的包装.这是一个视图,这意味着它不拥有字符串,因此不会复制和分配用于存储字符串的内存.

It is basically a wrapper around string objects. And it's a view, which means that it doesn't own the string and thus doesn't copy and allocate memory to store a string.

请注意,对于小字符串(还有文字),由于 SSO 因此开销很小.始终在进行优化之前先进行测量.

Note that for small strings (and also literals), std::string doesn't allocate too due to SSO and so the overhead is minimal. Always measure before optimizing.

这篇关于使用const char *作为map/unordered_map的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆