Home > Backend Development > C++ > Why Do `char*` Keys Fail in `std::map`, and How Can I Fix It?

Why Do `char*` Keys Fail in `std::map`, and How Can I Fix It?

Linda Hamilton
Release: 2024-12-26 04:49:15
Original
538 people have browsed it

Why Do `char*` Keys Fail in `std::map`, and How Can I Fix It?

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;
Copy after login

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;
    }
};
Copy after login

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:

map g_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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template