【发布时间】:2011-05-08 15:30:12
【问题描述】:
我试图弄清楚为什么以下代码不起作用,并且我假设这是使用 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;
}
【问题讨论】:
-
有时做正确的事一开始会很痛苦。将您的代码更改为使用
std:string一次,然后就开心了。 -
什么样的并发症?存在从 char* 到 std::string 的隐式转换。
-
您不能使用
char*作为映射键。请参阅my answer 为什么。 -
这似乎是由于not使用
std::string造成的不必要的并发症。 -
我不明白,为了使用二进制键,Map 是否不需要知道键是否相等而不是知道键的值“小于”另一个?