gpt4 book ai didi

c++ - 嵌套 std::map 的单行查找

转载 作者:行者123 更新时间:2023-12-05 08:21:54 24 4
gpt4 key购买 nike

假设我有一个 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;
}

关于c++ - 嵌套 std::map 的单行查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69744386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com