假设我有一个 std::map<int, std::map<int, std::string>>
, 如果在较短的语句中给定两个键,是否有直接查找字符串的方法?
一些语法糖:
std::map<int, std::map<int, std::string>> nested_map;
nested_map[1][3] = "toto";
int key1 = 1;
int key2 = 3;
std::string val;
auto it1 = nested_map.find(key1);
if (it1 != nested_map.end())
{
auto it2 = it1->second.find(key2);
if (it2 != it1->second.end())
{
val = it2->second;
}
}
编辑:我只是在寻找语法糖来节省一点输入,因为我的代码中有很多这样的嵌套映射。
Edit2:我不想失败。
最佳答案
像这样一个简单的(可能是内联的)函数怎么样:
using nested_map = std::map<int, std::map<int, std::string>>;
bool find_value(const nested_map& map, int key1, int key2, std::string& val)
{
auto it1 = nested_map.find(key1);
if(it1 == map.end()) return false;
auto it2 = it1->second.find(key2);
if(it2 == it1->second.end()) return false;
val = it2->second;
return true;
}
std::string val;
if(find_value(map, 1, 3, val))
{
// do something useful
}
替代版本,更短,但在内部使用异常:
bool find_value(const nested_map& map, int key1, int key2, std::string& val)
{
try { val = map.at(key1).at(key2); }
catch(...) { return false; }
return true;
}
https://stackoverflow.com/questions/69744386/