通过引用遍历节点的惯用方法
Idiomatic way to traverse nodes by reference
以一个字符串开头,该字符串表示我要从中检索数据的节点的路径,例如"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]);
}
});
应该按预期工作。
相关文章:
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 比较两个节点坐标的最佳方法是什么?
- 创建静态哨兵节点的正确方法是什么
- 删除节点方法实际上不会删除二叉搜索树中的节点.C++
- 链接列表的push_front和push_back方法似乎删除了节点
- 从不同的节点插件方法多次调用JS函数
- 如何将按钮添加到节点的属性编辑器面板,该面板调用该节点内的方法?
- 双向链表插入方法实现 - 正在搜索哪个节点
- 从基于矢量的二叉搜索树中删除节点的最佳方法
- 这是在双链表的第一个节点之后插入节点的正确方法吗?
- 使用类创建节点的方法
- 找到其他节点的最快方法
- 在图算法中,确定是否访问节点的最佳方法是什么?
- 节点.JS,C++模块:为什么当我尝试调用本地的长度方法时出现段错误<Array>?
- c ++作业 - 在链接列表代码中初始化节点的正确方法
- 有没有一种方便的方法可以从属性树中删除节点,同时保留其子节点
- C++将节点添加到链表的开头一次后失败.其他方法也有问题
- 从节点数组和边缘向量获取所有子树的最有效方法是什么
- C++ Get 方法不返回指向节点的指针
- C 节点本机扩展调用方法两次