问题
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:
- [MOST EXCELLENT article] https://thispointer.com/how-to-iterate-over-an-unordered_map-in-c11/
- [EXCELLENT GENERAL INFO on iterators] https://www.cplusplus.com/reference/iterator/
- [cplusplus.com
std::unordered_map
reference pg] https://www.cplusplus.com/reference/unordered_map/unordered_map/ - [cppreference.com
std::unordered_map
reference pg] https://en.cppreference.com/w/cpp/container/unordered_map
See also:
- How to use range-based for() loop with std::map?
来源:https://stackoverflow.com/questions/46945197/where-does-unordered-mapk-viterator-come-from