简体   繁体   English

如何在 Rust 中简洁地定义多维 Vec?

[英]How can I concisely define multidimensional `Vec`s in Rust?

When initializing a multidimensional Vec in Rust, I can use the vec!在Rust中初始化多维Vec时,我可以使用vec! -macro like this: - 像这样的宏:

vec![vec![0; 100]; 200]

However, this gets messy for Vec s of higher dimensions.但是,对于更高维度的Vec来说,这会变得很混乱。 Currently, I am using this:目前,我正在使用这个:

vec![vec![vec![vec![vec![vec![vec![vec![0; N-1]; N-1]; N-1]; N-1]; 2]; 2]; 2]; 2]

This is not very concise, and also the order in which the dimensions are written is reverse to the indexing order.这样不是很简洁,而且维度的书写顺序和索引顺序是相反的。 Is there a more concise way to do this?有没有更简洁的方法来做到这一点? I am looking for something like我正在寻找类似的东西

vec![0; 2, 2, 2, 2, N-1, N-1, N-1, N-1]

The ndarray crate allows you to have an N-dimensional array. ndarray crate 允许你拥有一个 N 维数组。 For anything above 6 dimensions, you can use the ArrayD type.对于 6 维以上的任何内容,您可以使用ArrayD类型。 You can create a dynamic dymension using IxDyn - documentation with examples .您可以使用带有示例IxDyn文档创建动态维度。

Example for a 7x7x7...x7 array initialization and element access: 7x7x7...x7 数组初始化和元素访问的示例:

    let mut array_7d = ArrayD::<f64>::zeros(IxDyn(&[7, 7, 7, 7, 7, 7, 7, 7]));
    let index = IxDyn(&[0, 0, 0, 0, 0, 0, 0, 0]);
    array_7d[&index] = 1.0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM