Home >Backend Development >C++ >How Can I Use Pointers as Keys in a std::map Correctly?

How Can I Use Pointers as Keys in a std::map Correctly?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 17:11:14619browse

How Can I Use Pointers as Keys in a std::map Correctly?

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, int> g_PlayerNames. Without specifying a comparison functor, the map compares char pointers, which may point to different memory locations even if they reference the same null-terminated string.

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!

Statement:
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