【发布时间】:2016-11-15 12:24:48
【问题描述】:
我目前正在使用我的自定义键创建自定义 std::unordered_map 声明:
class BASE_DLLSPEC ClientKey
{
private:
// this is always true initially until we call SetClientId
bool emptyId;
// both of these are guaranteed to be unique
QString m_connectId; // ip:port format
QString m_clientId; // {Uuid} format
// ----------
public:
ClientKey(const QString& connectId = "", const QString& clientId = "") :
emptyId(true), m_connectId(connectId), m_clientId(clientId)
{ }
void SetClientId(const QString& clientId)
{
m_clientId = clientId;
emptyId = false;
}
const QString& GetConnectId() const { return m_connectId; }
const QString& GetClientId() const { return m_clientId; }
bool operator==(const ClientKey& other) const
{
int comp1 = QString::compare(m_connectId, other.GetConnectId());
int comp2 = QString::compare(m_clientId, other.GetClientId());
return (comp1 == 0) ||
(!emptyId && comp2 == 0);
}
};
struct BASE_DLLSPEC ClientKeyHash
{
std::size_t operator()(const ClientKey& key) const
{
std::string connectId = key.GetConnectId().toStdString();
std::string clientId = key.GetClientId().toStdString();
std::size_t h1 = std::hash<std::string>()(connectId);
std::size_t h2 = std::hash<std::string>()(clientId);
return h1 ^ (h2 << 1);
}
};
struct BASE_DLLSPEC ClientKeyEqual
{
bool operator()(const ClientKey& lhs, const ClientKey& rhs) const
{
return lhs == rhs;
}
};
typedef std::unordered_map<ClientKey,
ClientPtr,
ClientKeyHash,
ClientKeyEqual> ClientMap;
我在迭代过程中很难找到特定的键。由于某种原因,当我传入一个键进行查找时,我的客户端对象永远不会被找到。
ClientKey key = Manager::ClientKey(connectId);
ClientManager& clientManager = Manager::ClientManager::GetInstance();
ClientMap::const_iterator clientIter = clientManager.GetClients().find(key);
即使key已经被插入,clientIter总是指向结束迭代器的位置。您是否认为这与必须在堆栈上重新创建这些 ClientKey 值然后将它们传递到映射中进行查找有关,还是我在其他地方有问题?感谢您的澄清和见解。
【问题讨论】:
-
我没有看到您为您的客户端密钥实现哈希函数,这很可能是问题所在。看到这个答案:stackoverflow.com/questions/17016175/…
-
看起来您允许比较相等的键具有不同的哈希值。这不可能。
标签: c++ unordered-map