rust swap vector elements
To swap elements in a Rust vector, you can use the swap
method provided by the Vec
type. This method takes two indices as arguments and swaps the elements at those indices in the vector. Here's an example:
fn main() {
let mut vec = vec![1, 2, 3, 4, 5];
vec.swap(1, 3);
println!("{:?}", vec); // Output: [1, 4, 3, 2, 5]
}
In this example, we create a mutable vector vec
containing the elements 1, 2, 3, 4, and 5. We then call the swap
method on the vector, passing in the indices 1 and 3. This swaps the elements at those indices, resulting in the vector [1, 4, 3, 2, 5]
. Finally, we print the vector to verify the swap.
Note that the indices in Rust start from 0, so the first element has an index of 0, the second element has an index of 1, and so on. Also, the vector must be mutable (mut
) in order to modify its elements.