3

从一个字符串开始,该字符串表示我要从中检索数据的节点的路径,例如“abc”。目前,我用来横穿节点层次结构以到达该节点的代码看起来像这样(可能无法编译,但你明白了):

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)

上面的代码似乎可以正常工作,但我想知道是否有更好的方法来进行节点横向分配。使用直接节点分配 ( currNode = currNode[key]),而不是 () 的指针/地址currNode = &((*currNode)[key]),似乎最终会在节点之间创建引用,而不是从一个节点遍历到下一个节点。

是否有“更清洁”或更惯用的方法来实现这一目标?

4

2 回答 2

1

现在没有办法做到这一点(这是一个我没有想到的用例),但这是个好主意。我提交了一个错误(http://code.google.com/p/yaml-cpp/issues/detail?id=189)。

于 2013-01-31T18:45:30.617 回答
1

我在做类似的事情,发现这个功能是前一段时间添加的,称为Node::reset()

所以,

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

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

应该按预期工作。

于 2017-02-12T03:07:01.593 回答