简体   繁体   English

提升c ++属性 - 如果key不存在则设置为false

[英]Boost c++ property - if key does not exist then set to false

I am new to json parsing with boost using the property tree. 我是json使用属性树解析boost的新手。

If I have this hash: 如果我有这个哈希:

foo = {'test1',true}

ptree pt;
bool v = pt.get<bool>("test2");

I need to check a key exists and if not set it to false. 我需要检查存在的密钥,如果没有将其设置为false。

How do I do that gracefully? 我该如何优雅地做到这一点?

Thanks 谢谢

  // bool optional
  boost::optional<bool> v = pt.get_optional<bool>("test2");

  // any type actually
  boost::optional<std::string> v2 = pt.get_optional<std::string>("test3");

  if (v) // key exists
    bool bool_value = v.get();
  else // not exists
    v.set(false);

From boost documentation you can try to find the key and if not_found() then you can push a new key. 从boost 文档中,您可以尝试找到密钥,如果not_found()则可以推送新密钥。

assoc_iterator not_found() ; assoc_iterator not_found(); Returns the not-found iterator. 返回未找到的迭代器。 Equivalent to end() in a real associative container. 相当于真实关联容器中的end()。

const_assoc_iterator not_found() const; const_assoc_iterator not_found()const; Returns the not-found iterator. 返回未找到的迭代器。 Equivalent to end() in a real associative container. 相当于真实关联容器中的end()。

assoc_iterator find(const key_type & key) ; assoc_iterator find(const key_type&key); Find a child with the given key, or not_found() if there is none. 查找具有给定键的子项,如果没有,则查找not_found()。 There is no guarantee about which child is returned if multiple have the same key. 如果多个孩子拥有相同的密钥,则无法保证返回哪个孩子。

const_assoc_iterator find(const key_type & key) const; const_assoc_iterator find(const key_type&key)const; Find a child with the given key, or not_found() if there is none. 查找具有给定键的子项,如果没有,则查找not_found()。 There is no guarantee about which child is returned if multiple have the same key. 如果多个孩子拥有相同的密钥,则无法保证返回哪个孩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM