如何识别未知密钥

如何识别未知密钥

本文介绍了使用YAML-cpp,如何识别未知密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该用例正在逐步浏览用YAML编写的配置文件.我需要检查每个键并相应地解析其值.我喜欢使用诸如doc["key"] >> value之类的随机访问方法的想法,但是我真正需要做的是警告用户配置文件中无法识别的密钥,以防万一它们例如拼写错误的密钥.我不知道如何在不遍历文件的情况下执行此操作.

The use case is stepping through a configuration file written in YAML. I need to check each key and parse its value accordingly. I like the idea of using random-access methods like doc["key"] >> value, but what I really need to do is warn the user of unrecognized keys in the config file, in case they, for example, misspelled a key. I don't know how to do that without iterating through the file.

我知道我可以使用YAML::Iterator来做到这一点

I know I can do this using YAML::Iterator, like so

for (YAML::Iterator it=doc.begin(); it<doc.end(); ++it)
{
   std::string key;
   it.first() >> key;
   if (key=="parameter") { /* do stuff, possibly iterating over nested keys */ }
   } else if (/* */) {
   } else {
       std::cerr << "Warning: bad parameter" << std::endl;
   }
}

但是有更简单的方法吗?我的方法似乎完全避开了YAML-cpp中内置的任何错误检查,并且似乎消除了随机访问密钥的所有简单性.

but is there a simpler way to do this? My way seems to completely circumvent any error checking built into YAML-cpp, and it seems to undo all the simplicity of randomly accessing the keys.

推荐答案

如果您担心某个键由于用户拼写错误而不在那,则可以使用FindValue:

If you're worried about a key not being there because the user misspelled it, you can just use FindValue:

if(const YAML::Node *pNode = doc.FindValue("parameter")) {
   // do something
} else {
   std::cerr << "Parameter missing\n";
}

如果您确实希望将地图中的所有键都排除在特定列表之外,那么您就必须在进行操作时进行迭代.

If you genuinely want to get all keys in the map outside of your specific list, then you'll have to iterate through as you're doing.

这篇关于使用YAML-cpp,如何识别未知密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:42