An idiomatic way to move nodes by reference

Starting with a string representing the path to the node I want to extract data from, like "abc". Currently, the code I am using for a cross node hierarchy to reach that node looks something like this (may not compile, but you get the idea):

string keyPath("a.b.c");
vector<string> keyPieces(split(keyPath, "."));

const YAML::Node *currNode = &rootNode;
for_each(begin(keyPieces), end(keyPieces), [&](const string &key)
{
    // for simplicity, ignore indexing on a possible scalar node
    // and using a string index on a sequence node
    if ((*currNode)[key])
    {
        currNode = &((*currNode)[key]);
    }
});

// assuming a valid path, currNode should be pointing at the node
// described in the path (i.e. currNode is pointing at the "c" node)

      

The above code works correctly, but I am wondering if there is a better way to perform a transversal assignment to node. Using direct node ( currNode = currNode[key]

) assignment instead of pointer / address ( currNode = &((*currNode)[key])

) seems to result in links being created between nodes, rather than going from one node to another.

Is there a "cleaner" or more idiomatic way to do this?

+3


source to share


2 answers


There is no way to do this now (this is a use case I haven't thought of), but it's a good idea. I have filed a bug ( http://code.google.com/p/yaml-cpp/issues/detail?id=189 ).



+1


source


I did something similar and found out that this feature was added sometime, called Node::reset()

So,



string keyPath("a.b.c");
vector<string> keyPieces(split(keyPath, "."));

const YAML::Node currNode = rootNode;
for_each(begin(keyPieces), end(keyPieces), [&](const string &key)
{
    if (currNode[key])
    {
        currNode.reset(currNode[key]);
    }
});

      

should work as intended.

+1


source







All Articles