Add iterator over neighbors of a vertex Graph::neighbors()

This commit is contained in:
2025-10-21 16:36:53 +02:00
parent 0826e140b8
commit dd76355a70
+23 -2
View File
@@ -13,10 +13,26 @@ pub struct VertexIncidenceHeader {
pub first_incidence: Option<Incidence>, pub first_incidence: Option<Incidence>,
} }
pub struct VertexNeighborIterator<'a> {
graph: &'a Graph,
incidence: Option<Incidence>,
}
impl<'a> Iterator for VertexNeighborIterator<'a> {
type Item = Vertex;
fn next(&mut self) -> Option<Self::Item> {
let incidence = self.incidence?;
self.incidence = self.graph.next_incidences[incidence.0];
Some(self.graph.incidence_vertices[incidence.0])
}
}
// TODO: Graph cannot support deleting vertices because of the external indices "Vertex". They could be made stable with e.g. slotmap or generational arena. // TODO: Graph cannot support deleting vertices because of the external indices "Vertex". They could be made stable with e.g. slotmap or generational arena.
// TODO: Graph fields must not be public. // TODO: Graph fields must not be public.
// TODO: Add functions to reserve memory for vertices and edges. // TODO: Add functions to reserve memory for vertices and edges.
// TODO: Add function to delete edges. // TODO: Add function to delete edges.
// TODO: Add iterator of edges.
pub struct Graph { pub struct Graph {
// TODO: Index 'incidence_headers' by a 'Vertex' instead of 'Vertex.0'? // TODO: Index 'incidence_headers' by a 'Vertex' instead of 'Vertex.0'?
pub incidence_headers: Vec<VertexIncidenceHeader>, pub incidence_headers: Vec<VertexIncidenceHeader>,
@@ -24,8 +40,6 @@ pub struct Graph {
pub incidence_vertices: Vec<Vertex>, pub incidence_vertices: Vec<Vertex>,
} }
// TODO: Add iterator of edges.
// TODO: Add iterator of vertex neighbors, see 'fn add_adjacent()'.
impl Graph { impl Graph {
pub fn new() -> Graph { pub fn new() -> Graph {
Graph { Graph {
@@ -90,6 +104,13 @@ impl Graph {
pub fn iter(&self) -> impl Iterator<Item = Vertex> { pub fn iter(&self) -> impl Iterator<Item = Vertex> {
(0..self.incidence_headers.len()).map(Vertex) (0..self.incidence_headers.len()).map(Vertex)
} }
pub fn neighbors(&self, v: Vertex) -> impl Iterator<Item = Vertex> {
VertexNeighborIterator {
graph: self,
incidence: self.incidence_headers[v.0].first_incidence,
}
}
} }
#[cfg(test)] #[cfg(test)]