Write a function to remove duplicate elements from a vector in Rust.
Write a function to remove duplicate elements from a vector in Rust.
22120-Jun-2023
Home / DeveloperSection / Forums / Write a function to remove duplicate elements from a vector in Rust.
Aryan Kumar
23-Jun-2023Sure, here is a function to remove duplicate elements from a vector in Rust:
Rust
This function first defines a function called remove_duplicates that takes a mutable reference to a Vec of i32 as input. The function first initializes a HashSet called seen_elements to store all the elements that have been seen. Then, the function creates a new vector called new_vector to store the elements that have not been seen. The function then iterates through the vector vector, checking if each element is in the seen_elements HashSet. If the element is not in the seen_elements HashSet, then the function adds the element to the new_vector vector and to the seen_elements HashSet. Finally, the function clears the vector vector and appends the new_vector vector to the vector vector.
The main function of the program then creates a vector called vector with the values 1, 1, 2, 3, 3, 4, 5, 5, 6. The function then calls the remove_duplicates function with the vector vector as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called remove_duplicates.rs and then compile it using the following command:
Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet