亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用char *作為std :: map中的鍵

使用char *作為std :: map中的鍵

C++
白板的微信 2019-08-19 10:23:04
使用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;}
查看完整描述

3 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

你需要給地圖提供一個比較仿函數,否則它會比較指針,而不是它指向的以空字符結尾的字符串。通常,只要您希望地圖鍵成為指針,就會出現這種情況。

例如:

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


查看完整回答
反對 回復 2019-08-19
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

你不能使用,char*除非你絕對100%確定你將使用完全相同的指針訪問地圖,而不是字符串。


例:


char *s1; // pointing to a string "hello" stored memory location #12

char *s2; // pointing to a string "hello" stored memory location #20

如果您訪問地圖,s1您將獲得與訪問地圖不同的位置s2。


查看完整回答
反對 回復 2019-08-19
  • 3 回答
  • 0 關注
  • 972 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號