将许多向量连接成一个新向量的最佳方法是什么? [英] Whats the best way to join many vectors into a new vector?

查看:51
本文介绍了将许多向量连接成一个新向量的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用其他向量的内容创建一个新向量,我目前正在这样做:

To create a new vector with the contents of other vectors, I'm currently doing this:

fn func(a: &Vec<i32>, b: &Vec<i32>, c: &Vec<i32>) {
    let abc = Vec<i32> = {
        let mut tmp = Vec::with_capacity(a.len(), b.len(), c.len());
        tmp.extend(a);
        tmp.extend(b);
        tmp.extend(c);
        tmp
    };

    // ...
}

有没有更直接/更优雅的方法来做到这一点?

Is there a more straightforward / elegant way to do this?

推荐答案

有一个 concat 方法可以用于这个,但是值需要是切片,或者可以借给切片,而不是&Vec<_> 如问题中所述.

There is a concat method that can be used for this, however the values need to be slices, or borrowable to slices, not &Vec<_> as given in the question.

一个例子,类似于问题:

An example, similar to the question:

fn func(a: &Vec<i32>, b: &Vec<i32>, c: &Vec<i32>) {
    let abc = Vec<i32> = [a.as_slice(), b.as_slice(), c.as_slice()].concat();

    // ...
}

然而,正如@mindTree 所指出的,使用 &[i32] 类型参数更加惯用,并且不需要转换.例如:

However, as @mindTree notes, using &[i32] type arguments is more idiomatic and removes the need for conversion. eg:

fn func(a: &[i32], b: &[i32], c: &[i32]) {
    let abc = Vec<i32> = [a, b, c].concat();

    // ...
}

SliceConcatExt::concat 是函数的更通用版本,可以将多个切片连接到 Vec.它将对每个切片的大小求和以预先分配正确容量的 Vec,然后重复扩展.

SliceConcatExt::concat is a more general version of your function and can join multiple slices to a Vec. It will sum the sizes each slice to pre-allocate a Vec of the right capacity, then extend repeatedly.

fn concat(&self) -> Vec<T> {
    let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
    let mut result = Vec::with_capacity(size);
    for v in self {
        result.extend_from_slice(v.borrow())
    }
    result
}

这篇关于将许多向量连接成一个新向量的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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