【发布时间】:2013-01-31 16:48:52
【问题描述】:
以一个字符串开头,该字符串表示我要从中检索数据的节点的路径,例如“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])) 的指针/地址,似乎最终会在节点之间创建引用,而不是从一个节点遍历到下一个节点。
是否有一种“更简洁”或更惯用的方式来实现这一点?
【问题讨论】: