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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
