问题
As known the following code is used to iterate map in C++
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
{
std::cout << itr->first << " => " << itr->second << '\n';
}
Where itr is declared as std::map::iterator. The members first and second are declared neither in std::map nor in std::iterator. Then how is it available for access?
回答1:
The elements of an std::map are std::pair<key_type, mapped_type>
, so de-referencing a map iterator gives you a reference to one of these.
It is the std::pair class template which has first
and second
members.
回答2:
The basic idea behind iterators is that they are "magical" objects used to access data, that behave like pointers do on an array - i.e. you use arithmetic operators (e.g. ++
and --
) to move around and you dereference (using *
and ->
) to access the data.
So, itr
is "like" a pointer to an std::pair<char, int>
, so you can access the data dereferencing it via the *
operator (which yields the key/value pair
) or with the ->
operator, as in your example.
来源:https://stackoverflow.com/questions/22061866/c-iterating-map