How do I compare a vector against a reversed version of itself?

前端 未结 2 842
情歌与酒
情歌与酒 2021-01-14 03:16

Why won\'t this compile?

fn isPalindrome(v: Vec) -> bool {
  return v.reverse() == v;
}

I get



        
2条回答
  •  温柔的废话
    2021-01-14 03:35

    Read up on the documentation for the function you are using:

    Reverse the order of elements in a slice, in place.

    Or check the function signature:

    fn reverse(&mut self)
    

    The return value of the method is the unit type, an empty tuple (). You can't compare that against a vector.


    Stylistically, Rust uses 4 space indents, snake_case identifiers for functions and variables, and has an implicit return at the end of blocks. You should adjust to these conventions in a new language.

    Additionally, you should take a &[T] instead of a Vec if you are not adding items to the vector.

    To solve your problem, we will use iterators to compare the slice. You can get forward and backward iterators of a slice, which requires a very small amount of space compared to reversing the entire array. Iterator::eq allows you to do the comparison succinctly.

    You also need to state that the T is comparable against itself, which requires Eq or PartialEq.

    fn is_palindrome(v: &[T]) -> bool
    where
        T: Eq,
    {
        v.iter().eq(v.iter().rev())
    }
    
    fn main() {
        println!("{}", is_palindrome(&[1, 2, 3]));
        println!("{}", is_palindrome(&[1, 2, 1]));
    }
    

    If you wanted to do the less-space efficient version, you have to allocate a new vector yourself:

    fn is_palindrome(v: &[T]) -> bool
    where
        T: Eq + Clone,
    {
        let mut reverse = v.to_vec();
        reverse.reverse();
        reverse == v
    }
    
    fn main() {
        println!("{}", is_palindrome(&[1, 2, 3]));
        println!("{}", is_palindrome(&[1, 2, 1]));
    }
    

    Note that we are now also required to Clone the items in the vector, so we add that trait bound to the method.

提交回复
热议问题