How do I return a Filter iterator from a function?

Rust 1.26 fn filter_one(input: &[u8]) -> impl Iterator<Item = &u8> { input.iter().filter(|&&x| x == 1) } fn main() { let nums = vec![1, 2, 3, 1, 2, 3]; let other: Vec<_> = filter_one(&nums).collect(); println!(“{:?}”, other); } Rust 1.0 fn filter_one<‘a>(input: &’a [u8]) -> Box<Iterator<Item = &’a u8> + ‘a> { Box::new(input.iter().filter(|&&x| x == 1)) } … Read more

Do STL iterators guarantee validity after collection was changed?

Depends on the container. e.g. if it’s a vector, after modifying the container all iterators can be invalidated. However, if it’s a list, the iterators irrelevant to the modified place will remain valid. A vector’s iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector … Read more

How can I iterate over two vectors simultaneously using BOOST_FOREACH?

Iterating over two things simultaneously is called a “zip” (from functional programming), and Boost has a zip iterator: The zip iterator provides the ability to parallel-iterate over several controlled sequences simultaneously. A zip iterator is constructed from a tuple of iterators. Moving the zip iterator moves all the iterators in parallel. Dereferencing the zip iterator … Read more

Closing a java.util.Iterator

Create a custom iterator which implement the AutoCloseable interface public interface CloseableIterator<T> extends Iterator<T>, AutoCloseable { } And then use this iterator in a try with resource statement. try(CloseableIterator iterator = dao.findAll()) { while(iterator.hasNext()){ process(iterator.next()); } } This pattern will close the underlying resource whatever happens: – after the statement complete – and even if … Read more

Iterators in C++ (stl) vs Java, is there a conceptual difference?

Perhaps a bit more theoretical. Mathematically, collections in C++ can be described as a half-open interval of iterators, namely one iterator pointing to the start of the collection and one iterator pointing just behind the last element. This convention opens up a host of possibilities. The way algorithms work in C++, they can all be … Read more

Java: how to get Iterator from String [duplicate]

One option is to use Guava: ImmutableList<Character> chars = Lists.charactersOf(someString); UnmodifiableListIterator<Character> iter = chars.listIterator(); This produces an immutable list of characters that is backed by the given string (no copying involved). If you end up doing this yourself, though, I would recommend not exposing the implementation class for the Iterator as a number of other … Read more