2

有没有一种简单的方法可以在不迭代的情况下使用 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 在 YAML 文件中的 goodKey 下。这很好用,但我想告诉用户无法识别的密钥是什么。不过,我不知道如何访问它。我在头文件中看不到任何赋予我该值的函数。我如何得到它?

4

1 回答 1

1

不一定有一个“无法识别的密钥”。例如,您的 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
于 2012-11-06T18:54:00.073 回答