gpt4 book ai didi

for-loop - 如何在循环内创建向量的向量?

转载 作者:行者123 更新时间:2023-12-03 11:32:31 26 4
gpt4 key购买 nike

我正在尝试使用for循环创建向量的向量。我尝试了以下设计,但没有成功:

// num_partitions is the primary vector, v is vector that contains a set of integers
// This function should return a Primary Vector that hold num_partitions of vectors

fn partition_data(num_partitions: usize, v: &Vec<usize>) -> Vec<Vec<usize>> {
let partition_size = v.len() / num_partitions;

// Create a vector that will contain vectors of integers
let mut xs: Vec<Vec<usize>> = Vec::new();

for j in 0..partition_size {
for i in 0..partition_size {
// create a new Vector and push elements to it
let mut x1: Vec<usize> = Vec::new();
x1.push(v[i]);
}
// push this new Vector the the Primary Vector
xs.push(x1);
}

// return primary vector
xs
}

最佳答案

Rust标准库中有一些方便的函数,它们已经完成了仅使用Iterators即可轻松实现此函数所需的大部分工作:

fn partition_data(num_partitions: usize, v: &Vec<usize>) -> Vec<Vec<usize>> {
let partition_size = v.len() / num_partitions;
v.chunks(partition_size)
.map(|chunk| chunk.to_vec())
.collect()
}
playground

关于for-loop - 如何在循环内创建向量的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65171822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com