Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare an array and a part of a vector?

Tags:

rust

I have an array and vector and the vector is populated in a loop. In each iteration of the loop, I want to check whether the last 4 elements of the vector is equal to 4 elements of the array. The size of the array is 4.

Is there a better way to do that than comparing their elements one by one? I'd like something like my_array == my_vector[4, -4]

like image 786
Alan Coromano Avatar asked May 22 '16 17:05

Alan Coromano


Video Answer


1 Answers

Is there a better way to do that than comparing their elements one by one?

Yes, you can compare a slice of the array with a slice of the vector:

fn main() {
    let a = [3, 4, 5, 6];
    let v = vec![0, 1, 2, 3, 4, 5, 6];
    assert_eq!(&a[..], &v[v.len() - 4..]);
}

A slice can be created with any range form. Here are some examples of creating slices:

fn main() {
    let v = vec![0, 1, 2, 3, 4, 5, 6];

    // indexes 0, 1, 2 (3 not included)
    assert_eq!(&[0, 1, 2], &v[..3]);

    // indexes 2, 3 (4 not included)
    assert_eq!(&[2, 3], &v[2..4]);

    // indexes 3, 4, ..until the last
    assert_eq!(&[3, 4, 5, 6], &v[3..]);

    // all indexes
    assert_eq!(&[0, 1, 2, 3, 4, 5, 6], &v[..]);
}
like image 153
malbarbo Avatar answered Oct 13 '22 14:10

malbarbo