Iterating Over a Vector
This lesson will teach you how to loop through a vector.
We'll cover the following
If it is desired to access each element of a vector, then it is possible to iterate over the elements of a vector using iter()
rather than using the indexes to access a particular element of a vector using the square bracket notation.
Iterate Using .iter()
Built-in Method
In the previous lesson, we learned to remove an element given an index. However, to remove a particular element, we
first need to find the index of that element and then call the remove
function passing that index.
For this we can use the .iter().position(|&e| e == element_name).unwrap()
.
Here,
-
iter()
is the built-in function that iterates over the elements of the vector. -
.position
is a built-in function that takes the element name to get the position of that element in the vector, i.e.,(|&e| e == element_name)
defines a variablee
with the value equal to the name of the element that we want to find. -
.unwrap()
is the built-in function.More details of
.unwrap()
will be covered in Enums chapter.
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy