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

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

相关文章:

c++ - 创建一个线程安全的原子计数器

assembly - x86中的BEXTR指令是如何工作的

azure-devops - Azure DevOps Pipeline NPM 安装任务因 nod

javascript - 如何在 sveltekit 应用程序中将菜单项设置为事件状态

android - 如何在 Room MVVM 架构中实现 Koin 依赖注入(inject)

r - 从 R 中的数据帧列表中进行子集化

java - 如何在实体中正确创建关系

angular - AWS Lambda@Edge Viewer 请求失败,返回 'The body

javascript - MongooseServerSelectionError:连接 ECONN

python - python解释器是否隐含地使用了中国余数定理?