[英]C++ iterating map
As known the following code is used to iterate map in C++ 众所周知,以下代码用于在C ++中迭代map
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 . 其中itr声明为std :: map :: iterator 。 The members first and second are declared neither in std::map nor in std::iterator . 第一个和第二个成员既不在std :: map中也不在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. std::map
的元素是std::pair<key_type, mapped_type>
,因此取消引用map迭代器会为您提供对其中一个的引用。
It is the std::pair
class template which has first
and second
members. 它是std::pair
类模板,它有first
和second
成员。
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. 因此, itr
“喜欢”指向std::pair<char, int>
的指针,因此您可以通过*
运算符(产生键/值pair
)或使用->
运算符访问解除引用它的数据,如在你的例子中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.