Two dimensional vectors in Rust
Asked Answered
C

4

24

Editor's note: This question predates Rust 0.1 (tagged 2013-07-03) and is not syntactically valid Rust 1.0 code. Answers may still contain valuable information.

Does anyone know how to create mutable two-dimensional vectors in Rust and pass them to a function to be manipulated?

This is what I tried so far:

extern crate std;

fn promeni(rec: &[u8]) {
    rec[0][1] = 0x01u8;
}

fn main() {
    let mut rec = ~[[0x00u8,0x00u8],
        [0x00u8,0x00u8]
    ];
    io::println(u8::str(rec[0][1]));
    promeni(rec);
    io::println(u8::str(rec[0][1]));
}
Citizenship answered 27/10, 2012 at 18:9 Comment(0)
H
31

You could use the macro vec! to create 2d vectors.

fn test(vec: &mut Vec<Vec<char>>){
    vec[0][0] = 'd';
    ..//
    vec[23][79] = 'd';
}

fn main() {

    let mut vec = vec![vec!['#'; 80]; 24];

    test(&mut vec);
}
Halsy answered 27/4, 2016 at 2:58 Comment(0)
I
7

If the functions that is going to manipulate are yours, you can create a custom struct with the helper methods to treat the vector as 2d:

use std::fmt;

#[derive(Debug)]
pub struct Vec2d<T> {
    vec: Vec<T>,
    row: usize,
    col: usize,
}

impl<T> Vec2d<T> {
    pub fn new(vec: Vec<T>, row: usize, col: usize) -> Self {
        assert!(vec.len() == row * col);
        Self { vec, row, col }
    }

    pub fn row(&self, row: usize) -> &[T] {
        let i = self.col * row;
        &self.vec[i..(i + self.col)]
    }

    pub fn index(&self, row: usize, col: usize) -> &T {
        let i = self.col * row;
        &self.vec[i + col]
    }

    pub fn index_mut(&mut self, row: usize, col: usize) -> &mut T {
        let i = self.col * row;
        &mut self.vec[i + col]
    }
}

impl<T: std::fmt::Debug> std::fmt::Display for Vec2d<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut str = String::new();
        for i in 0..self.row {
            if i != 0 {
                str.push_str(", ");
            }
            str.push_str(&format!("{:?}", &self.row(i)));
        }
        write!(f, "[{}]", str)
    }
}

fn main() {
    let mut mv = Vec2d::new(vec![1, 2, 3, 4, 5, 6], 2, 3);
    *mv.index_mut(1, 2) = 10;
    println!("Display: {}", mv);
    println!("Debug: {:?}", mv);
}

The associated function new creates the Vec2d, have two main methods (index and index_mut, so you can get a index value borrowed immut ou mut) and added a Display trait to visualise it better (but it is stored as Vec<>).

Intestinal answered 28/12, 2021 at 19:15 Comment(0)
L
4

Did you intend that all of the subarrays will have the length 2, as in this example? In that case, the type of the parameter should not be &[u8], which is a borrowed array of u8's, but rather &[[u8; 2]].

Longbow answered 28/10, 2012 at 4:55 Comment(1)
I might have them different lengths. What would I use in that case? Also what would I use if my arrays are not square? For example if I have 4 rows and 3 columns. Thanks.Citizenship
A
2

Using type annotation

let mut vec: Vec<Vec<i32>> = Vec::new();
Annmarie answered 3/10, 2023 at 20:34 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Ganoid

© 2022 - 2024 — McMap. All rights reserved.