首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用char*作为std::map中的键

使用char*作为std::map中的键
EN

Stack Overflow用户
提问于 2010-11-12 02:04:12
回答 6查看 84.4K关注 0票数 85

我试图找出为什么下面的代码不能工作,我假设这是使用char*作为键类型的问题,但我不确定如何解决它或为什么会发生它。我使用的所有其他函数(在HL2开发工具包中)都使用char*,所以使用std::string会造成许多不必要的复杂情况。

代码语言:javascript
复制
std::map<char*, int> g_PlayerNames;

int PlayerManager::CreateFakePlayer()
{
    FakePlayer *player = new FakePlayer();
    int index = g_FakePlayers.AddToTail(player);

    bool foundName = false;

    // Iterate through Player Names and find an Unused one
    for(std::map<char*,int>::iterator it = g_PlayerNames.begin(); it != g_PlayerNames.end(); ++it)
    {
        if(it->second == NAME_AVAILABLE)
        {
            // We found an Available Name. Mark as Unavailable and move it to the end of the list
            foundName = true;
            g_FakePlayers.Element(index)->name = it->first;

            g_PlayerNames.insert(std::pair<char*, int>(it->first, NAME_UNAVAILABLE));
            g_PlayerNames.erase(it); // Remove name since we added it to the end of the list

            break;
        }
    }

    // If we can't find a usable name, just user 'player'
    if(!foundName)
    {
        g_FakePlayers.Element(index)->name = "player";
    }

    g_FakePlayers.Element(index)->connectTime = time(NULL);
    g_FakePlayers.Element(index)->score = 0;

    return index;
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-11-12 02:07:38

您需要为map提供一个比较函数,否则它将比较指针,而不是它所指向的以null结尾的字符串。一般来说,只要你想让你的映射键成为一个指针,就会发生这种情况。

例如:

代码语言:javascript
复制
struct cmp_str
{
   bool operator()(char const *a, char const *b) const
   {
      return std::strcmp(a, b) < 0;
   }
};

map<char *, int, cmp_str> BlahBlah;
票数 148
EN

Stack Overflow用户

发布于 2010-11-12 02:10:26

两个C样式的字符串可以具有相同的内容,但位于不同的地址。map比较的是指针,而不是内容。

转换到std::map<std::string, int>的成本可能没有您想象的那么高。

但是,如果您确实需要使用const char*作为映射键,请尝试:

代码语言:javascript
复制
#include <functional>
#include <cstring>
struct StrCompare : public std::binary_function<const char*, const char*, bool> {
public:
    bool operator() (const char* str1, const char* str2) const
    { return std::strcmp(str1, str2) < 0; }
};

typedef std::map<const char*, int, StrCompare> NameMap;
NameMap g_PlayerNames;
票数 24
EN

Stack Overflow用户

发布于 2010-11-12 02:07:22

您正在将使用char *与使用字符串进行比较。它们是不一样的。

char *是指向字符的指针。归根结底,它是一个整数类型,其值被解释为char的有效地址。

字符串就是字符串。

容器工作正常,但作为密钥为char *、值为int的对的容器。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4157687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档