Efficiently insert or replace multiple elements in the middle or at the beginning of a Vec?

前端 未结 3 1943
滥情空心
滥情空心 2020-11-27 20:45

Is there any straightforward way to insert or replace multiple elements from &[T] and/or Vec in the middle or at the beginning of a

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 21:31

    As of Rust 1.21.0, Vec::splice is available and allows inserting at any point, including fully prepending:

    let mut vec = vec![1, 5];
    let slice = &[2, 3, 4];
    
    vec.splice(1..1, slice.iter().cloned());
    
    println!("{:?}", vec); // [1, 2, 3, 4, 5]
    

    The docs state:

    Note 4: This is optimal if:

    • The tail (elements in the vector after range) is empty
    • or replace_with yields fewer elements than range’s length
    • or the lower bound of its size_hint() is exact.

    In this case, the lower bound of the slice's iterator should be exact, so it should perform one memory move.


    splice is a bit more powerful in that it allows you to remove a range of values (the first argument), insert new values (the second argument), and optionally get the old values (the result of the call).

    Replacing a set of items

    let mut vec = vec![0, 1, 5];
    let slice = &[2, 3, 4];
    
    vec.splice(..2, slice.iter().cloned());
    
    println!("{:?}", vec); // [2, 3, 4, 5]
    

    Getting the previous values

    let mut vec = vec![0, 1, 2, 3, 4];
    let slice = &[9, 8, 7];
    
    let old: Vec<_> = vec.splice(3.., slice.iter().cloned()).collect();
    
    println!("{:?}", vec); // [0, 1, 2, 9, 8, 7]
    println!("{:?}", old); // [3, 4]
    

提交回复
热议问题