Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active February 15, 2024 11:20
Show Gist options
  • Save fancellu/177497bb906f3782e1152377d7bffbca to your computer and use it in GitHub Desktop.
Save fancellu/177497bb906f3782e1152377d7bffbca to your computer and use it in GitHub Desktop.
Rust dedupe Vec<T> without changing order
use std::collections::HashSet;
use std::hash::Hash;
fn unique_keep_order<T: Eq + Hash + Clone>(vec: Vec<T>) -> Vec<T> {
let mut seen = HashSet::new();
let mut output = Vec::with_capacity(vec.len());
for x in vec.into_iter() {
if seen.insert(x.clone()) {
output.push(x); // Use the original x
}
}
output
}
fn main() {
println!("{:?}", unique_keep_order(vec![1, 3, 1, 2, 2, 3]));
println!("{:?}", unique_keep_order::<i32>(vec![]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment