在可变 Vec 中弹出最后 N 个元素的惯用方法是什么? [英] What is the idiomatic way to pop the last N elements in a mutable Vec?

查看:50
本文介绍了在可变 Vec 中弹出最后 N 个元素的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向 RosettaCode 贡献 Rust 代码,以便同时学习 Rust 并为 Rust 社区做出贡献.在可变 Vec 中弹出最后一个 n 元素的最佳惯用方法是什么?

I am contributing Rust code to RosettaCode to both learn Rust and contribute to the Rust community at the same time. What is the best idiomatic way to pop the last n elements in a mutable Vec?

以下是我写的大致内容,但我想看看是否有更好的方法:

Here's roughly what I have written but I'm wanting to see if there's a better way:

fn main() {
    let mut nums: Vec<u32> = Vec::new();
    nums.push(1);
    nums.push(2);
    nums.push(3);
    nums.push(4);
    nums.push(5);

    let n = 2;
    for _ in 0..n {
        nums.pop();
    }

    for e in nums {
        println!("{}", e)
    }
}

(游乐场链接)

推荐答案

我建议使用 Vec::truncate:

I'd recommend using Vec::truncate:

fn main() {
    let mut nums = vec![1, 2, 3, 4, 5];

    let n = 2;
    let final_length = nums.len().saturating_sub(n);
    nums.truncate(final_length);

    println!("{:?}", nums);
}

另外,我

  • 使用了saturating_sub 处理向量中没有 N 元素的情况
  • 使用了vec![] 轻松构建数字向量
  • 一次性打印出整个向量

通常,当您弹出"某些东西时,您希望拥有这些值.如果你想要另一个向量中的值,你可以使用 <代码>Vec::split_off:

Normally when you "pop" something, you want to have those values. If you want the values in another vector, you can use Vec::split_off:

let tail = nums.split_off(final_length);

如果你想访问元素但不想创建一个全新的向量,你可以使用 Vec::drain:

If you want access to the elements but do not want to create a whole new vector, you can use Vec::drain:

for i in nums.drain(final_length..) {
    println!("{}", i)
}

这篇关于在可变 Vec 中弹出最后 N 个元素的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆