Sure, here is a Rust function to reverse the order of elements in a vector:
Rust
fn reverse_vector(vector: &mut Vec<i32>) {
// Initialize two iterators, one at the beginning of the vector and one at the end.
let mut i = 0;
let mut j = vector.len() - 1;
// Loop while the iterators haven't crossed.
while i < j {
// Swap the elements at the two iterators.
let temp = vector[i];
vector[i] = vector[j];
vector[j] = temp;
// Increment i.
i += 1;
// Decrement j.
j -= 1;
}
}
fn main() {
// Create a vector.
let mut vector = vec![1, 2, 3, 4, 5];
// Reverse the order of the elements in the vector.
reverse_vector(&mut vector);
// Print the vector.
for i in 0..vector.len() {
println!("{}", vector[i]);
}
}
This function first initializes two iterators, one at the beginning of the vector and one at the end. The function then loops while the iterators haven't crossed. In each iteration of the loop, the function swaps the elements at the two iterators. The function then increments i and decrements j. Finally, the function prints the vector.
To run this program, you can save it as a .rs file and then compile and run it using the following commands:
Code snippet
rustc reverse_vector.rs
./reverse_vector
This will print the following output:
Code snippet
5
4
3
2
1
This indicates that the order of the elements in the vector has been reversed.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to reverse the order of elements in a vector:
Rust
This function first initializes two iterators, one at the beginning of the vector and one at the end. The function then loops while the iterators haven't crossed. In each iteration of the loop, the function swaps the elements at the two iterators. The function then increments i and decrements j. Finally, the function prints the vector.
To run this program, you can save it as a
.rsfile and then compile and run it using the following commands:Code snippet
This will print the following output:
Code snippet
This indicates that the order of the elements in the vector has been reversed.