【问题标题】:how to store a collection of string as key and json as value in c++如何在c ++中将字符串集合存储为键和json作为值
【发布时间】:2015-09-14 13:54:41
【问题描述】:

我正在尝试在 cpp 中存储键值对的集合,其中 key 将是一个字符串,值也是如此 - 在我的例子中,一个表示对象的 JSON 字符串。

然后我需要使用 Key1 访问这个 json 对象 例如

Key1 = name1 值1 = {name:"Anil Gautam","age":25}

Key2 = name2 值2 = **strong text** = {name:"Sharan Gupta","age":26}

我要访问

{name:"Anil Gautam","age":25} 

当我输入“name1”时。我可以做些什么来将这种数据存储在 cpp 中。

【问题讨论】:

  • 澄清键和值都是字符串。仅包装示例中的键和值,以指示每个的全部内容都保存在字符串中。这似乎比使用单引号更好,这将是无效的 c++,或者通过转义内部双引号,只有在源文件中找到提供的数据时才会出现这种情况,而几乎可以肯定不是。

标签: c++ json


【解决方案1】:

看起来您应该将值数据放入一个结构中:

struct Value
{
  std::string name;
  unsigned int age;
};

现在有一个使用字符串和值结构的std::map

typedef std::map<std::string, Value> Map_Type;

插入是这样的:

Value v("Anil Gautam", 25);
Map_Type entries;
entries["name1"] = v;

获取值:

Value v2;
v2 = entries["name1"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2015-03-23
    • 1970-01-01
    • 2021-09-16
    • 2021-10-29
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多