0

This question is similar to 4d mapping in C++ with tuple

I have a 5d map that looks like this:

// initialize container, map
map<string, //Car brand
    map<int, //Year
        map<string, //Car model
            map<int, //Car number
                double>>>> Car_map; //Price

First I assign a value to the map:

Car_map["BMW"][2010]["3-series"][1] = "100";

Then I want to get the value I assigned to a string:

string Car_map_value= get<0>(Car_map["BMW"][2010].find("3-series")->second[1]);

But when I try to get the value I get this error:

|87|error: no matching function for call to 'get(std::map::mapped_type&)'|

How do I search trough a 5d map in C++?

Masudur Rahman
  • 1,585
  • 8
  • 16
KGB91
  • 630
  • 2
  • 6
  • 24

1 Answers1

1

You should break it down a bit:

auto &a = Car_map["BMW"]; // map<int, map<string, map<int, double>>>
auto &b = a[2010]; // map<string, map<int, double>>
auto &c = b.find("3-series")->second; // map<int, double>
auto &d = c[1]; //double

Then you see, that d is actually a double. You probably expected a std::tuple, because you used this in earlier questions ;)


As a note: If you use map::find, you probably want to check if the searched key exists. Because if "3-series" does not exist in your example you get UB.
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • 2
    `auto` and one letter variable names taken in alphabetical order, giving no hint of the type of the variable? Come on... – hyde Oct 27 '19 at 16:46
  • Yeah, I was too lazy and watched the type names in my IDE, I added the type names ^^ – Lukas-T Oct 27 '19 at 16:47
  • Indeed I did. Thanks for this nice example, now I understand maps much better! – KGB91 Oct 27 '19 at 16:47
  • 1
    The irony of using `auto` when you shouldn't, then having to write the real types in comments at the end of the line as a result. Why not just write the types to begin with? – Lightness Races in Orbit Oct 27 '19 at 17:20
  • @LightnessRacesinOrbit I tried it and found it harder to read. Originally I just wanted to show, an easier way to write this, where one can investigate the type in intellisense. – Lukas-T Oct 27 '19 at 17:29
  • @churill There is no way to use intellisense on that code snippet, not even if you copy-paste it to a C++ IDE, because it is just code snippet... Well, I guess you could combine it with the code in the question, and then add all the boilerplate to get it to compile but... SO answers are expected to be useful when just reading them in the browser. – hyde Oct 28 '19 at 11:43