0

我有全局 unordered_map,我在其中存储指向结构的指针。

使用 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('\0'); ++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;
4

1 回答 1

0

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

于 2013-08-08T21:46:52.103 回答