从一个字符串开始,该字符串表示我要从中检索数据的节点的路径,例如“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])
,似乎最终会在节点之间创建引用,而不是从一个节点遍历到下一个节点。
是否有“更清洁”或更惯用的方法来实现这一目标?