简体   繁体   中英

c++ multidimensional map: How to deference the 2nd key?

My question is how to access that 2nd key ( int d ), if try to deference that 2nd key means it shows not found.

Here's the code:

#include <bits/stdc++.h>

using namespace std;

struct mapp
{
    int a;
    string s1;
};

int main()
{
    map<char, map<int, struct mapp>> m2;

    char a = 'A';
    m2.insert(make_pair(a, map<int, struct mapp>()));

    int d = 3211;
    struct mapp m1;
    m1.s1 = "flower";
    m1.a = 1551;

    m2[a].insert(make_pair(d, m1));

    cout << m2.begin()->first << endl;
    cout << m2.begin()->second << endl;

    map<char, map<int, struct mapp>>::interator it = m2.begin();

    // cout << it->second << endl;
    // map<int, struct mapp>::iterator pt = it.second->first;
}

m2.begin()->second will give you another map which will require iterator again. As you havent pasted your code i had to type so above code is a little diff. but your answer only require last few lines.

#include <bits/stdc++.h>
using namespace std;

struct mapp
{
    int a;
    string s1;
};
int main()
{
    mapp m1;

    map<char, map<int,struct mapp>> m2;
    char a = 'A';

  //  m2.insert({a, map<int, mapp>()});

    int d = 123;
    m1.s1 = "hello";
    m1.a = 56;
    map<int, mapp>m3;
    m3.insert({d, m1});
    
    m2.insert({a,m3});
    cout << m2.begin()->first << "\n";
    
    cout << m2.begin()->second.begin()->first << "\n";   // d
    
    cout << m2.begin()->second.begin()->second.a << "\n"; // mapp a
    cout << m2.begin()->second.begin()->second.s1 << "\n"; // mapp s1
    
}

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