Is it accurate to state that a vector (among other collection types) is an Iterator
?
For example, I can loop over a vector in the following way, because it implements the Iterator
trait (as I understand it):
let v = vec![1, 2, 3, 4, 5]; for x in &v { println!("{}", x); }
However, if I want to use functions that are part of the Iterator
trait (such as fold
, map
or filter
) why must I first call iter()
on that vector?
Another thought I had was maybe that a vector can be converted into an Iterator
, and, in that case, the syntax above makes more sense.
An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished. When you use iterators, you don't have to reimplement that logic yourself. In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.
Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity.
Vector's iterators are random access iterators which means they look and feel like plain pointers. You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [] . std::vector<int> vec(10); std::vector<int>::iterator it = vec.
Use an iteratorAn iterator can be generated to traverse through a vector. vector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence.
No, a vector is not an iterator.
But it implements the trait IntoIterator
, which the for
loop uses to convert the vector into the required iterator.
In the documentation for Vec
you can see that IntoIterator
is implemented in three ways:
Vec<T>
, which is moved and the iterator returns items of type T
, &Vec<T>
, where the iterator returns shared references &T
,&mut Vec<T>
, where mutable references are returned.iter()
is just a method in Vec
to convert Vec<T>
directly into an iterator that returns shared references, without first converting it into a reference. There is a sibling method iter_mut()
for producing mutable references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With