C++ iterating map

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 06:19:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!