Is there a better way to making a 2d vector than this?

So I read in [this article] that it is better to avoid vectors like this: Vec<Vec>But I still need full acess to modify/update the vector, is there a better way than that? Sorry if this question is not very good, I am rather new here.(Rust Optimization.md · GitHub)

You can do like what they suggested in the link.

struct Matrix<T> {
    data: Vec<T>,
    num_columns: usize,
}

Then accessing/modifying the data could be done by using [num_columns*row + column], e.g.

impl<T> Matrix<T> {
    fn get(&self, col: usize, row: usize) -> T {
        let index = self.num_columns * row + col;
        self.data[index]
    }
}
1 Like

You may also want to check out this other thread about a very similar topic. It includes a couple Matrix<T> implementations and other suggestions.

2 Likes

This version probably doesn't compile and should probably be something like :

impl<T> Matrix<T> {
    pub fn get(&self, col: usize, row: usize) -> Option<&T> {
        let index = self.num_columns * row + col;
        self.data.get(index)
    }
}
2 Likes

Both of these versions should really be checking col:

impl<T> Matrix<T> {
    pub fn get(&self, col: usize, row: usize) -> Option<&T> {
        if col >= self.num_columns {
            return None;
        }
        let index = self.num_columns * row + col;
        self.data.get(index)
    }
}

impl<T: Copy> Matrix<T> {
    pub fn get_value(&self, col: usize, row: usize) -> T {
        assert!(col < self.num_columns);
        let index = self.num_columns * row + col;
        self.data[index]
    }
}
4 Likes

you could implement the Index trait fot get the elements:

1 Like

And IndexMut!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.