How to create map/unordered_map that will use const char*
as key directly?
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.
How do I declare a map object that uses const char*
directly without any overhead?
As an alternative to Rakete1111's
string_view
answer, you can equip your map with a suitable comparator (and hasher, for theunordered_map
):If you will use pointer as map keys it will compare keys based on pointer addresses, the same keys will be treated as different. So you will have to create your own comparison function when dealing with plain pointers, so you will better use some wrapper on plain pointers like other answer suggested.
You can use a
std::string_view
: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.
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.