如何在基于范围的 for 循环中找出此地图的类型?

问题描述

map <int,map <int,double> > adj_list_M;

我想运行一个基于范围的 for 循环,遍历这个地图。所以我想知道我可以用来获取元素引用的类型。

另外请验证这样做是否正确:

for( auto& ele : adj_list_M )

先谢谢你!

解决方法

如果要遍历容器中的所有键值对,请尝试:

for (const auto& ele : adj_list_M)
{
    std::cout<<"First key in adj_list_M "<<ele.first<<std::endl;
    for (const auto& sub_ele : ele.second)
    {
        std::cout<<"First key in sub_map : "<<sub_ele.first<<std::endl;
        std::cout<<"Second value in sub_map : "<<sub_ele.second<<std::endl;
    }
}

当然,因为有 const 关键字,所以它是只读的。如果您想通过引用编辑键值对中的值,请删除 const

,

类型是pair

[key,value] 的模板是

template<typename _T1,typename _T2>
    struct pair
    {
      typedef _T1 first_type;    /// @c first_type is the first bound type
      typedef _T2 second_type;   /// @c second_type is the second bound type

      _T1 first;                 /// @c first is a copy of the first object
      _T2 second;                /// @c second is a copy of the second object
     ... ...

因为key总是const,所以你可以使用下面的类型,
pair<const int,map<int,double>>
pair<const int,double>


    map<int,double> > adj_list_M;
    map<int,double> a{ { 1,1.1 },{ 2,2.2 } };
    adj_list_M[1] = a;

    for (pair<const int,double>>& ele : adj_list_M) {
        cout << typeid(ele).name() << endl;
        cout << ele.first << endl;
        for (pair<const int,double>& subele : ele.second) {
            cout << typeid(subele).name() << endl;
            cout << subele.first << ":" << subele.second << endl;
        }
    }

输出:

St4pairIKiSt3mapIidSt4lessIiESaIS_IS0_dEEEE
1
St4pairIKidE
1:1.1
St4pairIKidE
2:2.2