简体   繁体   English

STL map.find 返回所有元素

[英]STL map.find returns all the elements

Having a problem with undefined behaviour of STL map defined as follows: STL map 的未定义行为问题定义如下:

typedef bool (*SNAPSHOT_CALLBACK)(/*Some params here..*/);
typedef std::map<DWORD, SNAPSHOT_CALLBACK> SnapshotsMap;
SnapshotsMap m_mapCallbacks;

insertion:插入:

AddCallback(DWORD snapshotType, SNAPSHOT_CALLBACK callback)
    m_mapCallbacks.insert(std::pair<DWORD, SNAPSHOT_CALLBACK>(snapshotType, callback));

and query:和查询:

for (auto itr = m_mapCallbacks.find(cpyHeader->hdr); itr != m_mapCallbacks.end(); itr++)
{
   itr->second();
}

The problem that I'm having is on a single key search the iterator retrieves both keys that I have inserted.我遇到的问题是在单个键搜索中,迭代器会检索我插入的两个键。 My logs:我的日志:

Insert:
   Added callback type: 21000b Callback: 615F5AE0
   Added callback type: 210136 Callback: 615F5480
Query:
   Same iterator loop:
      Key to find: 21000b -> FOUND First: 21000b Second: 61da5ae0
      Key to find: 21000b -> FOUND First: 210136 Second: 61da5480

for some reason both elements get retrieved and there's no other modifications/thread on this map.出于某种原因,这两个元素都被检索到,并且此 map 上没有其他修改/线程。 Some help would be much appreciated:)一些帮助将不胜感激:)

Query should be查询应该是

// C++17 if construct
if (auto itr = m_mapCallbacks.find(cpyHeader->hdr); itr != m_mapCallbacks.end())
{
   itr->second();
}

or或者

// pre-C++17 (but C++11 for auto)
auto itr = m_mapCallbacks.find(cpyHeader->hdr);
if (itr != m_mapCallbacks.end())
{
   itr->second();
}

Your for iterates from found key until the end (so only (potentially) skips first elements)for从找到的键迭代直到结束(所以只有(可能)跳过第一个元素)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM