简体   繁体   中英

C++ STL unordered_map iterator problem

class Demo {
    struct FileData {
      int size;
      BYTE* buffer;
      DWORD flags;
    };

    typedef std::tr1::unordered_map<std::wstring,FileData> FileMap;
    FileMap m_fileMap;

    void myFunc()
    {
      std::wstring name = L"TestFile.png";
      FileMap::const_iterator iter = m_fileMap.find(name);
      std::cout << iter->first;
    }
};

Look at the code above. My problem is how does FileMap::const_iterator works. Does it make a copy of key(std::wstring) and value(FileData)? Or does it just holds pointers/reference to the key and value?

iterators are assignable and whilst keys and values in maps must be copyable, they do not need to be assignable.

Therefore it cannot use a copy in the general case, it must hold a pointer or reference internally.

In some cases eg ints it might specialise and use copies anyway.

It is an associated container:
This means that its stores Key/Value pairs internally (refereed to as the value_type).

The iterator provided overloads the * and -> operator to give you reference to the value_type. Which is a std::pair

Thus you can try this:

FileMap::const_iterator iter = m_fileMap.find(name);
if (iter != m_fileMap.end())
{
    FileMap::value_type const&   value = *iter;

    FileMap::key_type   const&   key   = iter->first;  /* value.first  */
    FileMap::data_type  const&   data  = iter->second; /* value.second */

    // Alternatively:
    // Assuming this hold: typedef std::tr1::unordered_map<std::wstring,FileData> FileMap;
    std::wstring const&    key1  = iter->first;
    FileData     const&    data1 = iter->second;
}

There is no guarantee. However, there are great chances that the iterator holds pointers. If you use mutable iterators, you can modify the data, so there is no copy made, and I can't think of a reason to make copies when using the const version.

However, does you code rely on such considerations or is it just out of curiosity?

iterator & const_iterator hold a pointer to your data. Here it should return m_fileMap.end() if your value is not found.

unordered_map holds a pair of the key\\value (by value), and the const_iterator holds a pointer to that pair. You dereference the iterator by accessing its members by ->.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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