Using Pointers as Keys in std::map
When using pointers as keys in a std::map, it's crucial to specify a comparison functor to enable comparisons based on the pointed values rather than the pointers themselves.
Problem:
In the code snippet provided, you're using std::map
Solution:
To resolve this, use a comparison function that compares the null-terminated strings pointed to by the char* keys. Here's an example:
struct cmp_str { bool operator()(char const *a, char const *b) const { return std::strcmp(a, b) < 0; } }; std::map<char *, int, cmp_str> g_PlayerNames;
In this example, the cmp_str struct defines an operator() function that compares the pointed strings using std::strcmp. This ensures that the map keys are compared based on their string values, not their pointer values. By using this comparison functor, you can correctly manipulate the map based on the underlying null-terminated strings.
The above is the detailed content of How Can I Use Pointers as Keys in a std::map Correctly?. For more information, please follow other related articles on the PHP Chinese website!