我试图找出为什么下面的代码不能工作,我假设这是使用char*作为键类型的问题,但我不确定如何解决它或为什么会发生它。我使用的所有其他函数(在HL2开发工具包中)都使用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;
}
发布于 2010-11-12 02:07:38
您需要为map提供一个比较函数,否则它将比较指针,而不是它所指向的以null结尾的字符串。一般来说,只要你想让你的映射键成为一个指针,就会发生这种情况。
例如:
struct cmp_str
{
bool operator()(char const *a, char const *b) const
{
return std::strcmp(a, b) < 0;
}
};
map<char *, int, cmp_str> BlahBlah;
发布于 2010-11-12 02:10:26
两个C样式的字符串可以具有相同的内容,但位于不同的地址。map
比较的是指针,而不是内容。
转换到std::map<std::string, int>
的成本可能没有您想象的那么高。
但是,如果您确实需要使用const char*
作为映射键,请尝试:
#include <functional>
#include <cstring>
struct StrCompare : public std::binary_function<const char*, const char*, bool> {
public:
bool operator() (const char* str1, const char* str2) const
{ return std::strcmp(str1, str2) < 0; }
};
typedef std::map<const char*, int, StrCompare> NameMap;
NameMap g_PlayerNames;
发布于 2010-11-12 02:07:22
您正在将使用char *
与使用字符串进行比较。它们是不一样的。
char *
是指向字符的指针。归根结底,它是一个整数类型,其值被解释为char
的有效地址。
字符串就是字符串。
容器工作正常,但作为密钥为char *
、值为int
的对的容器。
https://stackoverflow.com/questions/4157687
复制相似问题