加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用变体无限地嵌套地图

发布时间:2020-12-16 09:22:04 所属栏目:百科 来源:网络整理
导读:所以,我正在尝试制作无限可嵌套的地图,我可以在其中使用字符串,整数,布尔等. 这是我试过的: struct NMap;struct NMap : std::mapstd::string,std::variantNMAP*,std::string,std::any {};// ...NMap* something;something["lorem"]["ipsum"] = "Test"; ^ -
所以,我正在尝试制作无限可嵌套的地图,我可以在其中使用字符串,整数,布尔等.

这是我试过的:

struct NMap;
struct NMap : std::map<std::string,std::variant<NMAP*,std::string,std::any>> {};
// ...
NMap* something;
something["lorem"]["ipsum"] = "Test";
                  ^ - No such operator []

哪个是逻辑的,std :: variant没有[]运算符.无论如何在Nestable地图中使用std :: variant?

解决方法

简单而有点奇怪的东西:

#include <map>
#include <string>
#include <optional>

struct rmap : std::map<std::string,rmap>
{
    std::optional<std::string> value; // could be anything (std::variant,std::any,...)
};

通过一些糖和一些其他有品味的调整,你可以像你想要的那样使用它:

#include <map>
#include <string>
#include <optional>
#include <iostream>

struct rmap : std::map<std::string,rmap>
{
    using value_type = std::optional<std::string>;
    value_type value;
    operator const value_type&() const { return value; }
    rmap& operator=(value_type&& v) { value = v; return *this; }
    friend std::ostream& operator<<(std::ostream& os,rmap& m) { return os << (m.value ? *m.value : "(nil)"); }
};

int main()
{
    rmap m;
    m["hello"]["world"] = std::nullopt;
    m["vive"]["le"]["cassoulet"] = "Obama";

    std::cout << m["does not exist"]  << 'n';          // nil
    std::cout << m["hello"]["world"]  << 'n';          // nil
    std::cout << m["vive"]["le"]["cassoulet"]  << 'n'; // Obama
}

你可以用一些语法糖调整你的口味.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读