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?
The basic idea behind iterators is that they are "magical" objects used to access data, that behave like pointers do on an array - ie you use arithmetic operators (eg ++
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.
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.