In Rust's petgraph package, Is there a way to look up a node by its node weight?

149 Views Asked by At

I have a graph defined using Rust's petgraph crate. The node's weight type is String, denoting a node's "name". Is there a way to obtain the node index knowing only the node's weight (i.e. its name)? The crate's documentation does not seem to provide any such function.

Or do I need to maintain a name-to-index mapping myself on the side?

1

There are 1 best solutions below

0
Tonik On

I just encountered the same issue. I came up with a (not very pretty, but functional) solution:

let p_node = if let Some(idx) = graph.raw_nodes().iter().position(|x| x.weight == p)
{
        NodeIndex::new(idx)
} else {
        graph.add_node(p)
};

It's better to keep your own HashMap if you have a lot of nodes, but this was good enough for me.