这是Cout from a map with std::tuple
的后续问题我制作了一张小地图,称为BMW
。它包含键Usage
和Diesel
,如下所示。
#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;
}
无论如何,我可以从字符串中调用地图名称BMW
而不是写BMW.insert({"Usage", {"1", "2"}});
吗?像这样:
stirng Mycar;
Mycar.insert({"Usage", {"1", "2"}});
答案 0 :(得分:1)
用一个小例子来扩展Quentin的评论:
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"}});
}
也许您可以找到比mapMap
更好的名称;)