If I want to iterate through stl map, normally I use
for (it=my_map.begin();it!=my_map.end();it++)
{
}
I know that if (typeid(map<int,char>::iterator::value_type) == typeid(pair<const int,char>))
is TRUE ie value type of the iterator
of std::map(key_type,value_type)
is std::pair(const key_type,value_type)
.
But if I want to do
std::pair<const key_type,value_type> b=it;
compiler will give error?
This assignment std::pair<const key_type,value_type> b=*it;
works.
My question: What is the type of the iterator pointer to pair
or pair
?
Iterators are iterators. They are neither pointers, nor pairs. They are iterators.
"Dereferencing" 1 an iterator from a std::map<K, V>
will give you a std::pair<const K, V>&
2 , yes, but the iterator itself has its own type.
1) The *
and ->
operators are overloaded to perform this indirection since, again, an iterator is not actually a pointer in the C++ sense.
2) Or a const std::pair<const K, V>&
, if you started off with a std::map<K, V>::const_iterator
.
The answer to your question depends on how the iterator is implemented. As long as the type supports the operations required to be an iterator, the implementation is not something you should be concerned about. In the case of std::map
's iterators, chances are very good that they're in fact structs, not simply pointers. The reason is that typically maps are implemented as balanced trees, and so the iterators would need to know how to traverse the tree in-order. This requires a bit of book-keeping (parent nodes, maybe?)
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.