2012-11-06 113 views
1

是否有一种简单的方法可以在不使用迭代的情况下使用YAML-cpp获取密钥?我在说明中看到,我可以使用YAML-cpp迭代器类的first()方法,但我不需要实际迭代。我有一个可以通过缩进级别识别的关键字,但是现在我需要做的是抛出一个异常,如果关键字不是已知列表中的一个。我的代码目前看起来是这样的:在没有迭代的情况下获取密钥YAML-cpp

std::string key; 
if (doc.FindValue("goodKey") 
{ 
    // do stuff 
    key = "goodKey"; 
} else if (doc.FindValue("alsoGoodKey") { 
    // do stuff 
    key = "alsoGoodKey"; 
} else throw (std::runtime_error("unrecognized key"); 

// made it this far, now let's continue parsing 
doc[key]["otherThing"] >> otherThingVar; 
// etc. 

见,我需要钥匙串继续解析,因为otherThing是goodKey下的YAML文件。这工作正常,但我想告诉用户什么是无法识别的密钥。不过,我不知道如何访问它。我没有看到头文件中给出该值的任何函数。我如何得到它?

回答

0

不一定有一个“无法识别的密钥”。例如,你的YAML文件可能看起来像:

someKey: [blah] 
someOtherKey: [blah] 

,或者甚至可能是空的,例如{}。在前一种情况下,你想要哪一种?在后一种情况下,没有钥匙。

您在询问如何“在地图中获取密钥”,但地图可以有零个或多个密钥。

作为一个附注,您可以使用FindValue的实际结果来简化其中的一部分,假设您实际上不需要您抓取的密钥的名称。例如:

const YAML::Node *pNode = doc.FindValue("goodKey"); 
if(!pNode) 
    pNode = doc.FindValue("alsoGoodKey"); 
if(!pNode) 
    throw std::runtime_error("unrecognized key"); 

(*pNode)["otherThing"] >> otherThingVar; 
// etc 
+0

谢谢。我明白。 it.first()方法如何决定返回哪个键? – Fadecomic

+0

@Fadecomic,当你遍历地图时,它遍历键/值对。所以一次只能返回一个关键。它在地图中迭代的顺序未指定。 –

+0

示例“pNode = doc.FindValue(”goodKey“)|| doc.FindValue(”alsoGoodKey“)”似乎不正确,是一个bool,不是吗?或者yaml-cpp以某种方式重载它? – Suma

相关问题