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

新手上路,请多包涵

我试图弄清楚为什么以下代码不起作用,并且我假设这是使用 char* 作为键类型的问题,但是我不确定如何解决它或它为什么会发生。我使用的所有其他功能(在 HL2 SDK 中)都使用 char* 所以使用 std::string 会导致很多不必要的并发症。

 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;
}

原文由 Josh Renwald 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 682
2 个回答

您需要为映射提供一个比较函子,否则它正在比较指针,而不是它指向的以空字符结尾的字符串。通常,只要您希望地图键成为指针,就会出现这种情况。

例如:

 struct cmp_str
{
   bool operator()(char const *a, char const *b) const
   {
      return std::strcmp(a, b) < 0;
   }
};

map<char *, int, cmp_str> BlahBlah;

原文由 GWW 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以绑定一个执行 相同 工作的 lambda。

 #include <map>
#include <functional>
class a{
    std::map < const char*, Property*, std::function<bool(const char* a, const char* b)> > propertyStore{
        std::bind([](const char* a, const char* b) {return std::strcmp(a,b) < 0;},std::placeholders::_1,std::placeholders::_2)
    };
};

原文由 perimeno 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题