我最近开始将一个小型图形程序从c ++移植到Rust。在其中我使用四元树存储动态创建的地形。根据LOD和位置,在树中添加和删除节点。假设我使用Enum来表示树,添加和删除节点的最佳方法是什么?
答案 0 :(得分:1)
这些方面的东西会对你有用吗?这是一个我刚才做的通用树,但你可以用一个固定大小的动态矢量替换动态矢量(Vec),如果那是你的域问题(四叉树)。
use std::slice::Items;
enum Node<V> {
Parent(Vec<Node<V>>),
Leaf(V),
}
struct NodeIter<'a, V> {
stack: Vec<Items<'a,Node<V>>>,
}
impl<'a, V> NodeIter<'a, V> {
fn from(node: &'a Node<V>) -> NodeIter<'a, V> {
let mut stack = Vec::new();
match node {
&Parent(ref children) => stack.push(children.iter()),
&Leaf(_) => ()
}
NodeIter {
stack: stack
}
}
}
impl<'a, V> Iterator<&'a V> for NodeIter<'a, V> {
fn next(&mut self) -> Option<&'a V> {
while !self.stack.is_empty() {
match self.stack.mut_last().unwrap().next() {
Some(&Parent(ref vec)) => {
self.stack.push(vec.iter());
},
Some(&Leaf(ref v)) => {
return Some(v)
},
None => {
self.stack.pop();
}
}
}
None
}
}
impl<V> Node<V> {
fn append<'a>(&'a mut self, n: Node<V>) -> Option<&'a mut Node<V>> {
match self {
&Parent(ref mut children) => {
let len = children.len();
children.push(n);
Some(children.get_mut(len))
},
&Leaf(_) => None,
}
}
fn retain_leafs(&mut self, f: |&V|->bool) {
match self {
&Parent(ref mut children) => {
children.retain(|node| match node {
&Parent(_) => true,
&Leaf(ref v) => f(v),
})
},
&Leaf(_) => (),
}
}
fn iter<'a>(&'a self) -> NodeIter<'a, V> {
NodeIter::from(self)
}
}
fn main() {
let mut tree: Node<int> = Parent(Vec::new());
{
let b1 = tree.append(Parent(Vec::new())).unwrap();
b1.append(Leaf(1));
b1.append(Leaf(2));
b1.retain_leafs(|v| *v>1);
}
{
let b2 = tree.append(Parent(Vec::new())).unwrap();
b2.append(Leaf(5));
b2.append(Leaf(6));
}
for val in tree.iter() {
println!("Leaf {}", *val);
}
}