【问题标题】:How to create a Vector of Vectors within a For-Loop?如何在 For 循环中创建向量的向量?
【发布时间】:2023-04-08 12:08:01
【问题描述】:

我正在尝试使用 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 是严格的块范围的。由于您在最内层循环中声明x1,因此它只存在于所述最内层循环的一次迭代中。该声明需要提升一个范围。
  • 除此之外,您的代码没有多大意义:它只会创建 partition_size 向量,所有这些向量都包含来自输​​入向量的第一个 partition_size 项。
  • 输入&amp;Vec&lt;T&gt; 通常没有用处,&amp;[T] 提供了更多的调用者灵活性而没有任何缺点。
  • x1 应该在外部 for 循环中声明,而不是在内部循环中。这可能无法编译,因为xs.push(x1) 引用了该范围内不存在的变量。这不是 Rust 特有的问题,你会在 Java、Python、C++ 等中遇到相同或相似的问题。

标签: for-loop vector multidimensional-array rust iteration


【解决方案1】:

Rust 标准库中有一些方便的函数,它们已经完成了您只需使用迭代器轻松实现此函数所需的大部分功能:

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

【讨论】:

    【解决方案2】:

    这是您的问题的简化示例:

    let mut outer_vec: Vec<Vec<usize>> = Vec::new();
    for j in 0..5 {
      for i in 0..5 {     
        let mut inner_vec: Vec<usize> = Vec::new();
        inner_vec.push(1);
      }
      outer_vec.push(inner_vec);
    }
    

    inner_vec 在内部 for 循环中声明。 outer_vecouter for 循环中声明。由于 Rust 的scoping and ownership rulesinner_vec 在其作用域(内部for 循环)的末尾被销毁,因此外部作用域(外部for 循环)无法访问它:

    for i in 0..5 {
      let mut inner_vec: Vec<usize> = Vec::new();
      // inner_vec is valid from here ^
      inner_vec.push(1);
      // inner_vec is destroyed here, it's memory is freed
    }
    // inner_vec is now non-existent, so this fails:
    outer_vec.push(inner_vec);
    

    要解决此问题,您可以在外部范围内声明 inner_vec

    let mut inner_vec: Vec<usize> = Vec::new();
    for i in 0..5 {
      inner_vec.push(1);
    }
    // inner_vec and outer_vec are now in the same scope, so this is fine:
    outer_vec.push(inner_vec);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2021-12-08
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多