问题描述
我正在研究事件驱动的粒子模拟。下面的代码定义了 struct Event 并实现了二元堆所需的相等特征。这段代码可以工作,但由第二个构造函数 (new_event) 构建的对象事件具有冗余成员变量。我想要一个二进制堆,它可以与两个不同的事件结构一起使用,以避免这种冗余并提高我的代码效率,这对我的项目至关重要。 我可以使用 trait 来实现这一点吗?
pub struct Event
{
pub time: f64,pub event_type: EventType,pub particle_index1: usize,pub particle_index2: usize,pub particle_count1: usize,pub particle_count2: usize
}
impl Event
{
pub fn new_collision(time: f64,particle_index1: usize,particle_index2: usize,particle_count1: usize,particle_count2: usize) -> Self
{
Self {
time,particle_index1,particle_index2,event_type: EventType::EventCollision,particle_count1,particle_count2
}
}
pub fn new_event(time: f64,event_type: EventType,particle_count1:
usize) -> Self
{
Self {
time,particle_index2: 0,//REDUNDANT
event_type,particle_count2: 0 //REDUNDANT
}
}
}
impl PartialEq for Event
{
fn eq(&self,other: &Self) -> bool
{
self.time == other.time
}
}
impl Eq for Event{}
impl PartialOrd for Event
{
fn partial_cmp(&self,other: &Self) -> Option<Ordering>
{
other.time.partial_cmp(&self.time) //reverse order
}
}
impl Ord for Event
{
fn cmp(&self,other: &Self) -> Ordering
{
self.partial_cmp(other).unwrap()
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)