如何使用迭代器遍历表单 pair<int,pair<int,int>> 的映射

How to traverse a map of the form pair<int,pair<int,int>> with a iterator

本文关键字:int gt lt pair 映射 遍历 表单 何使用 迭代器      更新时间:2023-10-16

我定义了地图

map <int,pair<int,int>> hmap;

如果有pair(2,pair(3,4))如何获取 2 3 4 个值,itr->firstitr->second不起作用

如果有pair(2,pair(3,4))如何获取 2 3 4 个值 [从迭代器itrmap<int,pair<int, int>>

]

我想

itr->first           // 2
itr->second.first    // 3
itr->second.second   // 4

这是一个使用迭代器和基于范围的 for 语句的演示程序。

#include <iostream>
#include <map>
int main()
{
    std::map<int, std::pair<int, int>> hmap{ { 1, { 2, 3 } }, { 2, { 3, 4 } } };
    for (auto it = hmap.begin(); it != hmap.end(); ++it)
    {
        std::cout << "{ " << it->first
            << ", { " << it->second.first
            << ", " << it->second.second
            << " } }n";
    }
    std::cout << std::endl;
    for (const auto &p : hmap)
    {
        std::cout << "{ " << p.first
            << ", { " << p.second.first
            << ", " << p.second.second
            << " } }n";
    }
    std::cout << std::endl;
}

它的输出是

{ 1, { 2, 3 } }
{ 2, { 3, 4 } }
{ 1, { 2, 3 } }
{ 2, { 3, 4 } }