如何将向量与自身的反向版本进行比较? [英] How do I compare a vector against a reversed version of itself?

查看:62
本文介绍了如何将向量与自身的反向版本进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不编译?

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

我得到

error[E0308]: mismatched types
 --> src/main.rs:2:25
  |
2 |   return v.reverse() == v;
  |                         ^ expected (), found struct `std::vec::Vec`
  |
  = note: expected type `()`
             found type `std::vec::Vec<T>`


推荐答案

您正在使用的功能的文档


颠倒顺序

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

或检查函数签名:

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.

通常,Rust使用4个空格缩进,函数和变量的snake_case 标识符,在块末尾具有隐式返回。您应该以新的语言适应这些约定。

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.

此外,您还应该如果您不添加项目,请使用& [T] 代替 Vec< T>

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

要解决您的问题,我们将使用 iterators 比较切片。您可以获取切片的前进和后退迭代器,与反转整个数组相比,这需要很小的空间。 Iterator :: eq 允许您简洁地进行比较。

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.

您还需要声明 T 与自己具有可比性,因此需要 等式 PartialEq

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

fn is_palindrome<T>(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<T>(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]));
}

请注意,我们现在还需要 Clone 中的项目,因此我们将特征绑定添加到方法中。

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

这篇关于如何将向量与自身的反向版本进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆