Why does a doubly-reversed iterator act as if it was never reversed?

后端 未结 2 1985
灰色年华
灰色年华 2021-01-12 02:02

I have an input vector which contains numbers. In an output vector, I need to get a sequence of partial products but in right-to-left order. The last element of the output m

2条回答
  •  长发绾君心
    2021-01-12 02:46

    This behavior is actually explicitly described in the documentation:

    Notes about side effects

    The map iterator implements DoubleEndedIterator, meaning that you can also map backwards:

    […]

    But if your closure has state, iterating backwards may act in a way you do not expect. […]

    A way to solve this would be by adding an intermediary collect to be sure that the second rev does not apply on the Map:

    fn main() {
        let input = vec![2, 3, 4];
        let mut prod = 1;
        let p: Vec = input
            .iter()
            .map(|v| {
                prod *= v;
                prod
            }).rev()
            .collect::>()
            .into_iter()
            .rev()
            .collect();
        println!("{:?}", p);
    }
    

    But that requires an extra allocation. Another way would be to collect, and then reverse:

    fn main() {
        let input = vec![2, 3, 4];
        let mut prod = 1;
        let mut p: Vec = input
            .iter()
            .rev()
            .map(|v| {
                prod *= v;
                prod
            }).collect();
        p.reverse();
    
        println!("{:?}", p);
    }
    

提交回复
热议问题