我想弄清楚爲什麼下面的代碼不工作,並且我假設它是使用char *作爲鍵類型的問題,但是我不確定我如何解決它或爲什麼發生。我使用的所有其他功能(在HL2 SDK中)使用char*
,因此使用std::string
會導致很多不必要的複雜情況。使用char *作爲std :: map中的鍵
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;
}
有時候做正確的事情一開始就會受傷。改變你的代碼使用'std:string'一次,然後開心。 – 2010-11-11 18:06:42
有什麼樣的併發症?有一個從char *到std :: string的隱式轉換。 – tenfour 2010-11-11 18:07:50
您不得使用'char *'作爲映射鍵。請參閱[我的答案](http://stackoverflow.com/questions/4157687/using-char-as-a-key-in-stdmap/4157811#4157811)爲什麼。 – sbi 2010-11-11 18:17:42