从后到前填充矢量的最有效方法

时间:2016-05-11 03:47:58

标签: vector iterator rust

我正在尝试使用一系列值填充向量。为了计算第一个值,我需要计算第二个值,这取决于第三个值等等。

let mut bxs = Vec::with_capacity(n);

for x in info {
    let b = match bxs.last() {
        Some(bx) => union(&bx, &x.bbox),
        None => x.bbox.clone(),
    };
    bxs.push(b);
}
bxs.reverse();

目前我只是使用v.push(x)从前到后填充矢量,然后使用v.reverse()反转矢量。有没有办法在一次通过中做到这一点?

2 个答案:

答案 0 :(得分:5)

  

有没有办法一次性完成?

如果你不介意调整矢量,那就相对容易了。

struct RevVec<T> {
    data: Vec<T>,
}

impl<T> RevVec<T> {
    fn push_front(&mut self, t: T) { self.data.push(t); }
}

impl<T> Index<usize> for RevVec<T> {
    type Output = T;
    fn index(&self, index: usize) -> &T {
        &self.data[self.len() - index - 1]
    }
}

impl<T> IndexMut<usize> for RevVec<T> {
    fn index_mut(&mut self, index: usize) -> &mut T {
        let len = self.len();
        &mut self.data[len - index - 1]
    }
}

答案 1 :(得分:1)

使用alert(typeof startDate); // string alert(startDate); // "5/12/2016" var convertedStartDate = new Date(startDate); alert(convertedStartDate); // Thu May 12 2016 00:00:00 GMT-0500 (Central Standard Time) var startDatePlusNinetyDays = convertedStartDate.setDate(90); alert(startDatePlusNinetyDays); startDatePlusNinetyDays = new Date(startDatePlusNinetyDays); alert(startDatePlusNinetyDays); // Thu July 29 2016 00:00:00 GMT-0500 (Central Standard Time) 的解决方案如下。不安全版本的速度略高于使用objA = Immutable.Map({ a: 'test', b: Immutable.Map({ ... }) }); objB = Immutable.Map({ a: 'test', b: Immutable.Map({ ... }) }); objA.equals(objB); // not clear what the perf is on this 的安全版本的2倍。我们的想法是使用unsafe来分配向量,然后使用ptr::write(dst: *mut T, src: T)将元素写回到向量中。 offset(self, count: isize) -> *const T用于计算向量中的偏移量。

reverse()
相关问题