Question

Is there an easy way to get the key in a map using YAML-cpp without iterating? I see in the instructions that I can use the first() method of the YAML-cpp iterator class, but I don't need to actually iterate. I have a key that I can identify by indentation level, but what I need to do now is throw an exception if the key is not one of a known list. My code currently looks like this:

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.

See, I need the key string to continue parsing because otherThing is under goodKey in the YAML file. This works fine, but I'd like to tell the user what the unrecognized key was. I don't know how to access it, though. I don't see any functions in the header file that give me that value. How do I get it?

Was it helpful?

Solution

There isn't necessarily a single "unrecognized key". For example, your YAML file might look like:

someKey: [blah]
someOtherKey: [blah]

or it might even be empty, e.g., {}. In the former case, which one do you want? In the latter case, there are no keys.

You're asking for how to "get the key in a map", but maps can have zero or more keys.

As a side note, you can simplify some of this using the actual result of FindValue, assuming you don't actually need the name of the key that you grabbed. For example:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top