Where does unordered_map<K, V>::iterator come from?

ぐ巨炮叔叔 提交于 2021-02-19 05:40:07

问题


When I'm using a std::unordered_map<K, V> I know that the iterator to each key-value pair is of type std::unordered_map<K, V>::iterator. I also know that the iterator itself points to a pair<const K, V>. However, the only reason I know the iterator points to a pair is from looking at example code. Where is this behavior defined?

For example, if I go to the documentation at cppreference.com, I don't see where this behavior is explained. It only says that the member iterator is defined as a ForwardIterator.

So, my question is, how would a smart developer know what a std::unordered_map<K, V>::iterator actually represents? I'm sure there is some logical leap I'm missing.


回答1:


For STL containers

objects of type iterator when de-referenced return an object of type reference, which is a reference to an object of type value_type.

These are all defined inside the container.

Note the std::map is defined as a container. This information is part of this documentation.

https://en.cppreference.com/w/cpp/named_req/Container




回答2:


So, my question is, how would a smart developer know what a std::unordered_map<K, V>::iterator actually represents? I'm sure there is some logical leap I'm missing.

As of a few minutes ago, this page (https://en.cppreference.com/w/cpp/container/unordered_map) now shows the image below.

Notice the sections I highlighted. It now makes it crystal clear that an iterator is "to value_type", and a const iterator is "to const value_type". And value_type is specified as std::pair<const Key, T>. So, dereferencing an interator (*my_iterator) provides you an object of type value_type, which is std::pair<const Key, T> in this case--for a std::unordered_map. This should make it all clear now.

References:

Related links I've found really helpful as I've studied this, in this order from most-to-least helpful:

  1. [MOST EXCELLENT article] https://thispointer.com/how-to-iterate-over-an-unordered_map-in-c11/
  2. [EXCELLENT GENERAL INFO on iterators] https://www.cplusplus.com/reference/iterator/
  3. [cplusplus.com std::unordered_map reference pg] https://www.cplusplus.com/reference/unordered_map/unordered_map/
  4. [cppreference.com std::unordered_map reference pg] https://en.cppreference.com/w/cpp/container/unordered_map

See also:

  1. How to use range-based for() loop with std::map?


来源:https://stackoverflow.com/questions/46945197/where-does-unordered-mapk-viterator-come-from

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!