0

This is a follow up question from Cout from a map with std::tuple

I have made a small map that I call BMW. It contains the keys Usage and Diesel, as shown below.

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

int main()
{

    // initialize container
    map<string, tuple<string, string>> BMW;

    // insert elements
    BMW.insert({"Usage", {"1", "2"}});
    BMW.insert({"Disel", {"2", "3"}});

        string sFirst_value;
     string sSecond_value;

     //prints out the map
    for (const auto& x : BMW) {
        sFirst_value.assign(get<0>(BMW.find(x.first)->second)); 
        sSecond_value.assign(get<1>(BMW.find(x.first)->second));
        cout << x.first << "\n" << "Min: " << sFirst_value <<  "\n" << "Max: " << sSecond_value << "\n" << "\n";
    }

    return 0;
}

Is there anyway I can call the name of the map, BMW, from a string instead of writing BMW.insert({"Usage", {"1", "2"}});? Like this:

stirng Mycar;
Mycar.insert({"Usage", {"1", "2"}});
KGB91
  • 630
  • 2
  • 6
  • 24
  • 1
    No, but you can store it all in a `map>>`. – Quentin Oct 09 '19 at 13:16
  • How do I search that map? Do you have a small example (I am a newbie to C++)? – KGB91 Oct 09 '19 at 13:20
  • 3
    Unrelated, but if you are new to C++ you should take a look at [Why should I not include bits/stdc++.h?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). Just to point you in the right direction for future projects ;) – Lukas-T Oct 09 '19 at 14:04

1 Answers1

1

To expand on Quentin's comment with a small example:

std::map<std::string, std::map<std::string, std::tuple<std::string, std::string>>> mapMap;
std::string myCar = "BMW";
std::map<std::string, std::tuple<std::string, std::string>> &myCarMap = mapMap[myCar];
myCarMap.insert({"Usage", {"1", "2"}});

//Or simply
auto &bmwMap = mapMap["BMW"];
bmwMap.insert({"Usage", {"1", "2"}});
}

Probably you can find better names than mapMap though ;)

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • Thanks! Can you give some comments on line 3, I cannot follow that one. I don't understand what `&myCar` does? – KGB91 Oct 09 '19 at 15:35
  • 1
    It means, that the variable `myCarMap` is just a reference (almost like a pointer). Without the `&` we would copy the result of `mapMap[myCar];`. You can read more about this topic in [this question](https://stackoverflow.com/questions/1943276/what-does-do-in-a-c-declaration) – Lukas-T Oct 09 '19 at 17:04
  • One final question. If I want to find the car names in the first map, say BMW, how do I do that? This does not seem to work: `Test3.assign(get<0>(mapMap.find("BMW")->second));` – KGB91 Oct 11 '19 at 09:26
  • 1
    `mapMap.find("BMW")->second` is a map itself, not a tuple. – Lukas-T Oct 11 '19 at 09:52