通过引用遍历节点的惯用方法

Idiomatic way to traverse nodes by reference

本文关键字:方法 节点 引用 遍历      更新时间:2023-10-16

以一个字符串开头,该字符串表示我要从中检索数据的节点的路径,例如"a.b.c"。目前,我用来遍历节点层次结构以到达该节点的代码如下所示(可能无法编译,但您明白了):

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])),似乎最终会在节点之间创建引用,而不是从一个节点横向到下一个节点。

有没有一种"更干净"或更惯用的方法来实现这一点?

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

我正在做类似的事情,发现这个功能是前段时间添加的,叫做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]);
    }
});

应该按预期工作。