如何在C++中提取树迭代
how to extract a tree iteration in C++
我已经重复了好几次类似的代码。伪代码是这样的:
stack.push(root)
while stack size > 0
node = stack.pop()
if condition_1
if node is leaf
if condition_2
// do something,
// for example, push node into a vector and return the vector
else
stack.push(children of node)
或者像这样:
stack.push(root)
while stack size > 0
node = stack.pop()
if condition_1
if node is leaf
if condition_2 // or no condition_2 and return true directly
return true
else
stack.push(children of node)
return false
这两个代码段之间的区别在于,第一个代码段迭代所有叶节点,而第二个代码段具有中断逻辑。通常我做的主要工作是condition_2
及其范围。其他台词只是在重复自己。那么有没有办法用C++或任何其他语言提取这种树迭代循环呢?
正如我正确理解的那样,您希望拥有此算法的通用版本。
我不知道你想使哪些部分成为通用的,所以这是一个非常简单的解决方案,其中一切都是通用的。
template <class NodeType, class TraversalPredicate, class LeafPredicate,
class TerminalPredicate, class ChildrenGetter>
bool findIf(NodeType *root, TraversalPredicate shouldTraverse,
LeafPredicate isLeaf, TerminalPredicate shouldFinish,
ChildrenGetter getChildren) {
std::stack<NodeType *> stack;
stack.push(root);
while (not stack.empty()) {
auto *node = stack.top();
stack.pop();
if (not shouldTraverse(node))
continue;
if (isLeaf(node)) {
if (shouldFinish(node)) {
return true;
}
} else {
for (auto *child : getChildren(node)) {
stack.push(child);
}
}
}
return false;
}
我希望这就是你要找的!
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 从迭代器中提取数字
- 如何在C++中提取树迭代
- 正则表达式使用提升令牌迭代器在单引号和括号之间提取值
- 从 std::copy 和 std::copy_n 中提取输入迭代器
- 提取类的模板参数并迭代它们的最紧凑方法是什么
- C++:从只能通过迭代器访问的数据类型中高效地提取元素子集
- 使用迭代器从向量中提取子向量
- <T> 来自 istream 的迭代器,无格式提取
- 如何迭代vector并在每次迭代中提取最小值?