我想弄清楚为什么下面的代码不工作,并且我假设它是使用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