What does iterator-gt;second mean?(iterator-second 是什么意思?)
问题描述
在 C++ 中,std::map<>::iterator 的类型是什么?
In C++, what is the type of a std::map<>::iterator?
我们知道 std::map::iterator 类型的对象 it 有一个重载的 operator -> 返回一个 std::pair*,并且 std::pair<> 有一个 first 和第二个成员.
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.
但是,这两个成员对应的是什么,为什么我们必须以 it->second 的形式访问存储在 map 中的值?
But, what do these two members correspond to, and why do we have to access the value stored in the map as it->second?
推荐答案
我相信你知道一个 std::vector<X> 存储了一大堆 X代码>对象,对吧?但是如果你有一个 std::map,它实际存储的是一大堆 std::pair.这正是地图的本质 - 它将键和关联的值配对在一起.
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.
当您迭代 std::map 时,您正在迭代所有这些 std::pair.当您取消引用其中一个迭代器时,您会得到一个包含键及其关联值的 std::pair.
When you iterate over a std::map, you're iterating over all of these std::pairs. 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();
在这里,如果您现在执行 *it,您将获得地图中第一个元素的 std::pair.
Here, if you now do *it, you will get the the std::pair for the first element in the map.
现在类型 std::pair 让您可以访问它的元素通过两个成员:first 和 second.因此,如果您有一个名为 p 的 std::pair,则 p.first 是一个 X 对象和 p.second 是一个 Y 对象.
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.
所以现在您知道取消引用 std::map 迭代器会给您一个 std::pair,然后您可以使用 first访问它的元素代码> 和 <代码> 秒代码>.例如,(*it).first 将为您提供密钥,而 (*it).second 将为您提供值.这些等价于 it->first 和 it->second.
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 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:iterator->second 是什么意思?
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
