Search code examples
yaml-cpp

Determine the number of items in a list using the yaml-cpp new api


Is there a way to determine the number of items in a YAML list, or check if an entry exists using the new yaml-cpp api? For instance, say I have the list

Food:
  - pizza: 270
  - ice_cream: 90
  - fruit: 30

How can I determine the number of foods there are? Also, is there a way to check if a food is present or not in the YAML string? I know I could try to index to the food like root_node["Foods"]["fruit"].as<int>() and catch an exception if fruit doesn't exist, but is there a function similar to FindValue() in the old api (http://code.google.com/p/yaml-cpp/wiki/HowToParseADocument) to check if an entry exists?


Solution

  • To get the number of foods, use

    root_node["Food"].size();
    

    To check if a food is present or not is a little trickier in your example, because it's a sequence of maps, each with a single key/value pair. (This is often used to create an ordered map.) You'd just have to loop through each entry and check if it's what you want:

    bool does_food_exist(const std::string& name) {
        for(std::size_t i=0;i<root_node["Food"].size();i++) {
            if(root_node["Food"][i][name])
                return true;
        }
        return false;
    }
    

    If you meant, instead, to actually have an actual map, then your YAML file should look like:

    Food:
      pizza: 270
      ice_cream: 90
      fruit: 30
    

    In this case, checking if a food exists is easy:

    if(root_node["Food"]["fruit"]) {
        // "fruit" exists
    } else {
        // it doesn't exist
    }