简体   繁体   中英

C++ iterating map

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 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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM