2

Random access to the elements is not allowed.

let vec = vec![1,2,3,4,5,6,7,8,9,0];
let n = 3;
for v in vec.iter().rev().take(n) {
    println!("{}", v);
}
// this printed: 0, 9, 8
// need: 8, 9, 0

for v in vec.iter().rev().skip(n).rev() does not work.

3

I think the code you wrote does what you're asking it to. You are reversing the vec with rev() and then you're taking the first 3 elements of the reversed vector (therefore 0, 9, 8)

To obtain the last 3 in non-reversed order you can skip to the end of the vector minus 3 elements, without reversing it:

let vec = vec![1,2,3,4,5,6,7,8,9,0];
let n = vec.len() - 3;
for v in vec.iter().skip(n) {
    println!("{}", v);
}
  • Assume that the vector of 1000 elements. You will need skip 997 elements, then display the remaining 3 elements. I want to skip 3 elements from end, then print 3 elements, total: 6 moves. – vigu Oct 23 '15 at 16:19
  • @vigu iterators do not allow you to produce the same element twice, so you cannot iterate backwards and then iterate forwards over the same items again. – Shepmaster Oct 23 '15 at 17:26
  • @Shepmaster compiler optimizes skip the first 1000 elements? – vigu Oct 23 '15 at 17:46
2

Neither skip nor take yield DoubleEndIterator, you have to either:

  • skip, which is O(N) in the number of skipped items
  • collect the result of .rev().take(), and then rev it, which is O(N) in the number of items to be printed, and requires allocating memory for them

The skip is obvious, so let me illustrate the collect:

let vec = vec![1,2,3,4,5,6,7,8,9,0];
let vec: Vec<_> = vec.iter().rev().take(3).collect();
for v in vec.iter().rev() {
    println!("{}", v);
}

Of course, the inefficiency is due to you shooting yourself in the foot by avoiding random access in the first place...

1

Based on the comments, I guess you want to iterate specifically through the elements of a Vec or slice. If that is the case, you could use range slicing, as shown below:

let vec = vec![1,2,3,4,5,6,7,8,9,0];
let n = vec.len() - 3;
for v in &vec[n..] {
    println!("{}", v);
}

The big advantage of this approach is that it doesn't require to skip through elements you are not interested in (which may have a big cost if not optimized away). It will just make a new slice and then iterate through it. In other words, you have the guarantee that it will be fast.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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