#Iterating a VecDeque

9 messages · Page 1 of 1 (latest)

proper granite
#

Hi! I have the following problem:

  • I have a VecDeque
  • Given an element at an index, I want to iterate to the beginning of the VecDeque from that, and also to the end

So basically I want to get two iterators from the VecDeque, such that given it contains these elements [1, 2, 3, 4, 5, 6, 7], and the start index 3 (element "4"), I need two iterators that produce [3, 2, 1] and [5, 6, 7] respectively.
How would I go about doing that?

analog timber
#

?play ```rust
use std::collections::VecDeque;

fn main() {
let x: VecDeque<i32> = [1, 2, 3, 4, 5, 6, 7].into_iter().collect();
for i in x.iter().skip(3 + 1) {
println!("{}", i);
}
for i in x.iter().take(3).rev() {
println!("{}", i);
}
}

dreamy pikeBOT
#
5
6
7
3
2
1
elder silo
#

stick a .rev() in there too

analog timber
#

there we go

strange ravine
#

you could just do

for i in [0..n] {
  v[i]
}
for i in [n..v.len()].rev() { v[i] }
analog timber
#

knew I missed something

proper granite
#

Ayee, thanks! Didn't even know you could combine take and rev like that.

lost relic
#

It has a requirement for both DoubleEndedIter and ExactSizeIter, because it bases the element it takes in the len() method, from DoubleEndedIter,