无序映射返回NULL值

Unordered Map return NULL value

本文关键字:NULL 返回 映射 无序      更新时间:2023-10-16

我有全局无序映射,在这里我存储指向结构的指针。

使用COM事件处理程序将数据添加到映射中:

const _bstr_t oTicker(structQuoteSnap.bstrSymbol, false);
const RecentInfoMap::const_iterator it = mapRecentInfo->find(oTicker);
RecentInfo* ri;
if (it == mapRecentInfo->end()) {
    ri = new RecentInfo;        
    _tcsncpy_s(ri->Name, _countof(ri->Name), oTicker, _TRUNCATE);
    const size_t tickerLen = oTicker.length() + 1;
    const LPTSTR ticker = new TCHAR[tickerLen];
    _tcsncpy_s(ticker, tickerLen, oTicker, _TRUNCATE);
    (*mapRecentInfo)[ticker] = ri;
} else {
    ri = it->second;
}

在另一种方法中,我通过它的密钥获得地图的值:

const RecentInfoMap::const_iterator it = g_mapRecentInfo.find(pszTicker);
if (it == g_mapRecentInfo.end()) return nLastValid + 1;
const RecentInfo* const ri = it->second;    
assert(ri != NULL);
curDateTime.PackDate.Hour = ri->nTimeUpdate / 10000;

有时断言失败是因为ri为NULL。我不知道为什么会发生这种事。似乎有一个有效的代码。请给我一个建议。

有无序的映射函子和定义:

struct KeyHash {
    size_t operator()(const LPCTSTR&) const;
};
struct KeyEquals {
    bool operator()(const LPCTSTR&, const LPCTSTR&) const;
};
size_t KeyHash::operator()(const LPCTSTR& key) const {
    size_t hash = 2166136261U;
    for (LPCTSTR s = key; *s != _T(''); ++s) {
        hash = (hash ^ static_cast<size_t>(*s)) * 16777619U;
    }
    return hash;
};

bool KeyEquals::operator()(const LPCTSTR& x, const LPCTSTR& y) const {
    return _tcscmp(x, y) == 0;
};

typedef unordered_map<LPCTSTR, RecentInfo*, KeyHash, KeyEquals> RecentInfoMap;

您的哈希值取决于结构的内容。可能在某个时候,您更改了结构的内容,这将导致无序映射的内部结构不一致。什么会导致奇怪的行为对于同一实例,哈希值不能及时更改