2

Having a VecDeque deq and an item, how can I find out if deq contains item? I can do it with an iterator:

deq.iter().find(|e| e == item).is_none()

But this is a lot of code. I just want to say deq.contains(item), but VecDeque has no such method (edit: not true anymore, see my answer). Any alternatives?

  • I'd assume that Vec and VecDeque don't expose this method because it will always have to be an O(n) operation for these data structures. Maybe a different data structure would be more appropriate for your case? – Shepmaster Feb 23 '16 at 20:33
  • 1
    @Shepmaster in fact, Vec does expose contains() through its deref to a slice: here. – Vladimir Matveev Feb 23 '16 at 20:41
  • @VladimirMatveev that's what I get for assuming! – Shepmaster Feb 23 '16 at 21:25
4

The simpler way would probably be

deq.iter().any(|e| e == item)

but there seems to be no easier way.

  • You could create a Contains extension trait and implement it for VecDeque (and other collections?) using this code. Then you get the shorter code, but still being aware of the algorithmic issues. – Shepmaster Feb 23 '16 at 20:33
4

In Rust 1.12 a contains method was stabilized for LinkedList and VecDeque. Therefore the correct answer now is the obvious one:

deq.contains(item)
3

As Vladimir Matveev pointed out to me in comments, a slice has a contains method, so you could also use that on the inner slices:

let (a, b) = deq.as_slices();
a.contains(item) || b.contains(item)

As I mentioned in another comment, you can make a trait to give you the nice interface:

trait Contains<T> {
    fn contains(&self, item: &T) -> bool;
}

impl<T> Contains<T> for VecDeque<T>
    where T: PartialEq
{
    fn contains(&self, item: &T) -> bool {
        let (a, b) = self.as_slices();
        a.contains(item) || b.contains(item)
    }
}

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.