Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无序映射返回空值_C++_Null_Unordered Map - Fatal编程技术网

C++ 无序映射返回空值

C++ 无序映射返回空值,c++,null,unordered-map,C++,Null,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 Recen

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

使用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;
struct-KeyHash{
size_t运算符()(const LPCTSTR&)const;
};
结构键等于{
布尔运算符()(常量LPCTSTR&,常量LPCTSTR&)常量;
};
size\u t KeyHash::operator()(const LPCTSTR&key)const{
大小\u t散列=2166136261U;
对于(LPCTSTR s=key;*s!=_T('\0');++s){
散列=(散列^static_cast(*s))*16777619U;
}
返回散列;
};
bool KeyEquals::operator()(常量LPCTSTR&x,常量LPCTSTR&y)常量{
返回_tcscmp(x,y)==0;
};
typedef无序地图近景地图;

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

当这种情况发生在我身上时,我总是怀疑某个地方有一个rouge[]访问,这会将值初始化为NULL,无论它是否实际在映射中。我对此表示怀疑。通常,将映射封装在类中有助于防止您使用
[]
运算符,而应始终调用查找函数。你只想写一次
find
代码。你们都是对的。使用运算符[]是非常危险的,因为当通过映射中不存在的键进行访问时,它会将新值(我的代码的指针不正确)放入映射。现在我的代码运行良好!是的,我更改了结构的字段,但我不明白为什么散列键和结构值之间存在依赖关系。