Vec Insert And Remove Keep Order

Use insert and remove for order-preserving edits in the middle of a Vec, and know the O(n) shift cost that separates them from push, pop, and swap_remove.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    let mut queue = vec!["build", "test", "deploy"];

    // insert(索引, 值):插入点及之后元素整体右移,顺序保留
    queue.insert(1, "lint");
    println!("after insert: {queue:?}");

    // remove(索引):取走元素,其后元素左移补位
    let pulled = queue.remove(2);
    println!("removed: {pulled}, now: {queue:?}");

    // 越界索引 panic:生产代码先用 get 校验或保证长度
    println!("len: {}", queue.len());

    // 与 push/pop 的 O(1) 不同,中部操作是 O(n):
    // 高频中部编辑应改用 VecDeque
    queue.insert(queue.len(), "release"); // 等价 push
    println!("final: {queue:?}");
}

What the code does

Count the function main as the entire surface area of Vec Insert And Remove Keep Order.

Applying it

The demo output is labeled (after insert:, removed:, len:), so every printed line maps back to its originating operation.

Statements that matter

let mut queue = vec!["build", "test", "deploy"];
queue.insert(queue.len(), "release"); // 等价 push
println!("final: {queue:?}");
let pulled = queue.remove(2);

Interactive Tools for This Topic

FAQ

What does Vec Insert And Remove Keep Order print when run?
No setup needed: run the file and look for labeled lines like `after insert:`, `removed:`, `len:` in the output.