iterator-> second是什么意思? [英] What does iterator->second mean?
问题描述
在C ++中, std :: map<> :: iterator
的类型是什么?
我们知道类型 std :: map< A,B> :: iterator
的对象 it
运算符 - >
,其返回 std :: pair< A,B> *
$ c> std :: pair<> 有一个第一
和第二
但是,这两个成员对应于什么,为什么我们必须访问存储在映射中的值为 我确定你知道 当你遍历一个 这里,如果现在 现在类型< a href =http://en.cppreference.com/w/cpp/utility/pair> it-> c>
std :: 向量< X>
存储整个 X
对象,对吧?但是如果你有一个 std :: map< X,Y>
,它实际上存储的是一大堆 std :: pair< const X ,Y>
。
std :: map
,你将遍历所有这些 std :: pair
s。当你取消引用这些迭代器之一时,你会得到一个 std :: pair
,其中包含键及其关联的值。
std :: map< std :: string,int> m = / * fill it * /;
auto it = m.begin();
* it
,您将获得地图中第一个元素的 std :: pair
。
std :: pair
允许您访问其元素通过两个成员:第一
和第二
。因此,如果您有 std :: pair< X,Y>
调用 p
, p .first
是 X
对象和 p.second
是 c> std :: map
std :: map
迭代器给你一个 std :: pair
,然后可以使用首先
和第二
。例如,(* it).first
将为您提供密钥,(* it).second
价值。这些等同于 it->第一
和 it->第二
。 In C++, what is the type of a std::map<>::iterator
?
We know that an object it
of type std::map<A,B>::iterator
has an overloaded operator ->
which returns a std::pair<A,B>*
, and that the std::pair<>
has a first
and second
member.
But, what do these two members correspond to, and why do we have to access the value stored in the map as it->second
?
I'm sure you know that a std::vector<X>
stores a whole bunch of X
objects, right? But if you have a std::map<X, Y>
, what it actually stores is a whole bunch of std::pair<const X, Y>
s. That's exactly what a map is - it pairs together the keys and the associated values.
When you iterate over a std::map
, you're iterating over all of these std::pair
s. When you dereference one of these iterators, you get a std::pair
containing the key and its associated value.
std::map<std::string, int> m = /* fill it */;
auto it = m.begin();
Here, if you now do *it
, you will get the the std::pair
for the first element in the map.
Now the type std::pair
gives you access to its elements through two members: first
and second
. So if you have a std::pair<X, Y>
called p
, p.first
is an X
object and p.second
is a Y
object.
So now you know that dereferencing a std::map
iterator gives you a std::pair
, you can then access its elements with first
and second
. For example, (*it).first
will give you the key and (*it).second
will give you the value. These are equivalent to it->first
and it->second
.
这篇关于iterator-> second是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!