iterator->second 是什么意思?

2022-01-10 00:00:00 iterator c++ stl

在 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 让您可以访问它的元素通过两个成员:firstsecond.因此,如果您有一个名为 pstd::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 和 <代码> 秒.例如,(*i??t).first 将为您提供密钥,而 (*i??t).second 将为您提供值.这些等价于 it->firstit->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.

相关文章