Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use all but the last element from an iterator

Tags:

iterator

rust

I want to split a Vec into some parts of equal length, and then map over them. I have an iterator resulting from a call to Vec's chunks() method. This may leave me with a part that will be smaller than other parts, which will be the last element generated by it.

To be sure that all parts have equal length, I just want to drop that last element and then call map() on what's left.

like image 877
Innot Kauker Avatar asked Jan 04 '18 19:01

Innot Kauker


People also ask

How do I get the iterator to the last element in a list?

The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element. By past the last element it is meant that the iterator returned by the end() function return an iterator to an element which follows the last element in the list container.

How do you know if an iterator is last element?

You can check it just like you do in the while condition: if ( ! iter. hasNext()) { // last iteration ... }

How do you loop through a list from the last element in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.


2 Answers

As Sebastian Redl points out, checking the length of each chunk is the better solution for your specific case.

To answer the question you asked ("Use all but the last element from an iterator"), you can use Iterator::peekable to look ahead one. That will tell you if you are on the last item or not and you can decide to skip processing it if so.

let things = [0, 1, 2, 3, 4];

let mut chunks = things.chunks(2).peekable();
while let Some(chunk) = chunks.next() {
    if chunks.peek().is_some() {
        print!("Not the last: ");
    } else {
        print!("This is the last: ")
    }

    println!("{:?}", chunk);
}

To be sure that all parts have equal length, I just want to drop that last element

Always dropping the last element won't do this. For example, if you evenly chunk up your input, then always dropping the last element would lose a full chunk. You'd have to do some pre-calculation to decide if you need to drop it or not.

like image 131
Shepmaster Avatar answered Oct 04 '22 09:10

Shepmaster


You can filter() the chunks iterator on the slice's len() being the amount you passed to chunks():

let things = [0, 1, 2, 3, 4];

for chunk in things.chunks(2).filter(|c| c.len() == 2) {
    println!("{:?}", chunk);
}

As of Rust 1.31, you can use the chunks_exact method as well:

let things = [0, 1, 2, 3, 4];

for chunk in things.chunks_exact(2) {
    println!("{:?}", chunk);
}

Note that the returned iterator also has the method remainder if you need to get the uneven amount of items at the very end.

like image 25
Sebastian Redl Avatar answered Oct 04 '22 10:10

Sebastian Redl