我最近一直在使用Petgraph为节点和自定义边创建带有Structs的简单图,但是我遇到了一个问题,我不确定它是来自库还是Rust。
我有一个图,其中我有多个节点,每个节点都有一个名称。然后,我将节点的所有索引(类型为NodeIndex)都放在一个向量中,因为佩特图没有给出图中的所有节点的函数。然后,我想要创建一个给定字符串的函数,它返回与名称匹配的节点的索引。
我的问题是,包含节点的向量中的类型似乎发生了变化。我将其存储为NodeIndex,但是类型以某种方式自行更改为u32,而不需要更改任何内容。由于它是自动变化的,所以我不能在佩特图函数中传递值,因为它们需要NodeIndex作为输入,而不是u32。
下面的代码是我到目前为止所得到的,并且在函数find_node_index_with_name中出现了问题,即使我将NodeIndex的向量作为输入传递给它,类型似乎也会发生变化,所以当我迭代它时,我也应该得到NodeIndex。
use petgraph::adj::NodeIndex;
use petgraph::stable_graph::StableGraph;
use petgraph::dot::Dot;
#[derive(Clone,Debug,Default)]
struct ControlBloc
{
name:String,
value:u32,
}
fn create_bloc(name:String,value:u32) -> ControlBloc
{
ControlBloc
{
name,
value,
}
}
fn find_node_index_with_name(gr:StableGraph<ControlBloc,u32> , nodes:Vec<NodeIndex> , name_search:String) -> Option<NodeIndex>
{
for i in 0..nodes.len()
{
if gr.node_weight(nodes[i]).unwrap().name == name_search
{
return nodes[i];
}
}
return None;
}
fn main() {
let mut graph = StableGraph::<ControlBloc,u32>::new();
let m = create_bloc(String::from("Main"),10);
let b1 = create_bloc(String::from("sub1"),20);
let b2 = create_bloc(String::from("sub2"),30);
let main = graph.add_node(m);
let sub1 = graph.add_node(b1);
let sub2 = graph.add_node(b2);
let all_nodes = vec![main,sub1,sub2];
println!("{:?}",find_node_index_with_name(graph, all_nodes, String::from("Main")));
}我有点搞不懂为什么这些类型会改变。
谢谢您的投入!
发布于 2022-07-18 13:45:52
graph.add_node()返回一个petgraph::graph::NodeIndex。但是used petgraph::adj::NodeIndex似乎是一种不同的类型(不要问我为什么),因此类型不匹配。
我冒昧地修改了您的代码,以便在您使用拥有值的地方使用引用。
use petgraph::graph::NodeIndex; // graph not adj
use petgraph::stable_graph::StableGraph;
#[derive(Clone, Debug, Default)]
struct ControlBloc {
name: String,
value: u32,
}
fn create_bloc(
name: String,
value: u32,
) -> ControlBloc {
ControlBloc { name, value }
}
fn find_node_index_with_name(
gr: &StableGraph<ControlBloc, u32>,
nodes: &[NodeIndex],
name_search: &str,
) -> Option<NodeIndex> {
nodes
.iter()
.map(|n| *n)
.find(|n| gr.node_weight(*n).unwrap().name == name_search)
/*
for i in 0..nodes.len() {
if gr.node_weight(nodes[i]).unwrap().name == name_search {
return Some(nodes[i]);
}
}
None
*/
}
fn main() {
let mut graph = StableGraph::<ControlBloc, u32>::new();
let m = create_bloc(String::from("Main"), 10);
let b1 = create_bloc(String::from("sub1"), 20);
let b2 = create_bloc(String::from("sub2"), 30);
let main = graph.add_node(m);
let sub1 = graph.add_node(b1);
let sub2 = graph.add_node(b2);
let all_nodes = vec![main, sub1, sub2];
for n in ["Main", "sub1", "sub2"] {
println!("{:?}", find_node_index_with_name(&graph, &all_nodes, n));
}
}
/*
Some(NodeIndex(0))
Some(NodeIndex(1))
Some(NodeIndex(2))
*/https://stackoverflow.com/questions/73022935
复制相似问题