【问题标题】:Unordered Map return NULL value无序映射返回 NULL 值
【发布时间】:2013-08-10 18:46:04
【问题描述】:

我有全局 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;

【问题讨论】:

  • 当这种情况发生在我身上时,我总是怀疑某处有一个 rouge [] 访问,无论它是否真的在地图中,它都会将值初始化为 NULL。
  • 我同意这一点。通常,将地图封装在类中以防止您使用 [] 运算符会很有帮助 - 而是始终调用您的查找函数。您只想编写一次 find 代码。
  • 你们俩都是对的。使用 operator[] 非常危险,因为当通过不在地图中的键访问时,它会将新值(我的代码的错误指针)放入地图。现在我的代码可以正常工作了!

标签: c++ null unordered-map


【解决方案1】:

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

【讨论】:

  • 是的,我更改了结构的字段,但我不明白为什么哈希键和结构值之间存在依赖关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多