What does iterator->second mean?

后端 未结 2 2023
[愿得一人]
[愿得一人] 2020-12-22 16:59

In C++, what is the type of a std::map<>::iterator?

We know that an object it of type std::map::iterator has

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 17:52

    I'm sure you know that a std::vector stores a whole bunch of X objects, right? But if you have a std::map, what it actually stores is a whole bunch of std::pairs. 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::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

    std::map 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 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.

提交回复
热议问题