キーカスタムとunordered_map:私は私の反復中の特定のキーを見つけるの困難を抱えている検索キー::私は現在、私のカスタムキーとカスタムの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);
キーがすでに挿入されていても、clientIterは常に終了イテレータの位置を指します。これは、スタック上にこれらのClientKey値を再作成してからルックアップのためにマップに渡す必要がある、または別の場所で問題が発生することに関連していると思いますか?解明と洞察をいただきありがとうございます。まず
私はあなたのクライアントキーのハッシュ関数を実装していませんが、それはおそらく問題です。この回答を参照してください:http://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key –
それはあなたが等しいと比較するキーが異なるハッシュこれはおそらくうまくいかない。 –