简体   繁体   中英

How do I find out the type of this map in a range based for loop?

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

I want to run a range based for loop, iterating through this map. So I want to know the type I can use for getting the references of the elements.

Also please verify whether this is correct for doing that :

for( auto& ele : adj_list_M )

Thank you in advance!

If you want to loop through all the key value pairs in your container, try:

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;
    }
}

Of course, because of the const keyword, it is read-only. Remove the const if you want to edit the values in your key-value pair by reference.

The type is pair

the [key, value] 's template is

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
     ... ...

As key is always const , you can use the type below,
pair<const int, map<int, double>>
pair<const int, double>


    map<int, 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, map<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;
        }
    }

output:

St4pairIKiSt3mapIidSt4lessIiESaIS_IS0_dEEEE
1
St4pairIKidE
1:1.1
St4pairIKidE
2:2.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM