Home > Backend Development > C++ > How Can I Use `char*` Effectively as Keys in a C `std::map`?

How Can I Use `char*` Effectively as Keys in a C `std::map`?

Patricia Arquette
Release: 2024-12-23 17:52:14
Original
429 people have browsed it

How Can I Use `char*` Effectively as Keys in a C   `std::map`?

Using char* Effectively as std::map Keys

In C , using char* as a key in std::map can pose challenges. Consider the following code snippet that attempts to find an unused player name:

std::map<char*, int> g_PlayerNames;

int PlayerManager::CreateFakePlayer()
{
    // ...
    for(std::map<char*, int>::iterator it = g_PlayerNames.begin(); it != g_PlayerNames.end(); ++it)
    {
        // ...
    }
    // ...
}
Copy after login

This code may not function as intended because the default comparison for char* within std::map compares the pointers themselves, not the actual null-terminated strings they point to.

Resolution

To address this issue, you must provide a comparison functor to the map. This functor should compare the 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;
   }
};

map<char *, int, cmp_str> g_PlayerNames;
Copy after login

By incorporating the cmp_str functor, the map now compares the actual strings, allowing the intended logic to operate correctly.

Remember, this technique applies to any scenario where you intend to use pointers as keys in std::map. By providing a comparison functor, you ensure that the map operates as desired, comparing the actual values represented by the pointers.

The above is the detailed content of How Can I Use `char*` Effectively as Keys in a C `std::map`?. 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