The Perplexity of char* Keys in std::map
When dealing with hash-based containers like std::map, understanding key types is crucial. A peculiar issue arises when using char* as a map key, as illustrated in the following code:
std::map<char*, int> g_PlayerNames;
This code attempts to store Player names (char*) as keys and corresponding integers as values. However, when searching for an entry using a known name, the comparison fails, leading to unexpected results.
The root cause lies in the peculiar nature of char as a key. std::map compares keys by default using the less-than operator (<). For char pointers, however, this comparison checks the pointer addresses rather than the strings they point to.
To resolve this issue, we need to provide a custom comparison function that operates on the actual strings, not the pointers. Introducing a struct like the following enables us to do this:
struct cmp_str { bool operator()(char const *a, char const *b) const { return std::strcmp(a, b) < 0; } };
By providing this custom comparison function, we instruct the std::map to compare char* keys based on the strings they reference, ensuring correct key matching during lookups and insertions.
So, instead of using the original map definition, we modify it to include the comparison function:
mapg_PlayerNames; With this modification, the player name lookup and update logic functions as intended, utilizing the comparison function to match char* keys based on their string contents.
The above is the detailed content of Why Do `char*` Keys Fail in `std::map`, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!