如何获得链接列表中的当前和上一个项目?

时间:2019-05-28 16:41:56

标签: data-structures struct rust

我正在Rust中编写一个地图生成器,它将世界划分成多个部分,然后在这些部分中创建房间以连接这些房间。我通常要做的是有一个列表,然后在遍历该列表时获取父项(如果有),然后运行一些代码以连接这些房间。

我正努力遍历列表并获取父项。

这是我当前拥有的数据结构:

struct MapSectionPosition {
    x: f32,
    y: f32,
}

struct MapSectionRect {
    top_left: MapSectionPosition,
    top_right: MapSectionPosition,
    bottom_right: MapSectionPosition,
    bottom_left: MapSectionPosition,
}

struct MapSection {
    width: f32,
    height: f32,
    points: MapSectionRect,
}

struct RoomExit {
    position: MapSectionPosition,
}

struct Room {
    width: f32,
    height: f32,
    exit: RoomExit,
}

此刻我正在使用链接列表:

let mut rooms: LinkedList<Room> = LinkedList::new();

let room = Room {
    width: section.width / 4.0,
    height: section.height / 4.0,
    exit: RoomExit {
        position: MapSectionPosition { x: 20.0, y: 20.0 },
    },
};

rooms.push_back(room);

我正在努力迭代并获取父对象,因此我认为这可能不是正确的数据结构。

在周围玩耍的时候,我发现了一个骇人听闻的解决方案。希望这可以更好地说明我正在尝试做的事情,以及是否有更优雅的东西。

let mut previous_room: Option<&Room> = None;
for room in rooms.iter() {
    match previous_room {
        Some(p_room) => {
            println!("previous {}", p_room.width);
            println!("current {}", room.width);
            println!("connected");
        },
        None => {
            println!("no previous room");
        }
    }

    previous_room = Some(room);
}

有点优雅

如果房间是一个切片,那么我们可以使用windows方法创建一个迭代器来访问有问题的数据。

let mut iter = rooms[..].windows(2);
while let Some([prev, next]) = iter.next() {
    println!("prev - {}", prev.width);
    println!("next - {}", next.width);
    println!("done...")
}

这在Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc?

中已经得到回答

0 个答案:

没有答案