How to find the set of a vector?

How to find the set of a vector, i.e, given a vector, how to retrive the unique elements of the vector with its elements as f64 as their datatype ?

for example, let my vector be :

let numbers = vec![1.1, 1.1, 1.1, 2.2, 2.2, 2.2, 2.2, 3.3];

I want only the values [1.1, 2.2, 3.3].
Can someone suggest me a way to make it up !

I feel like the question must be missing some critical context, because the direct answer is so simple that it's nearly stated in the question: Just dump all the Vec elements into a HashSet.

HashSet in std::collections - Rust even has an example showing that let foo: HashSet<...> = somethingIterable.iter().cloned().collect(); is all the code you need to do this.

2 Likes

You can even hash references instead of cloning if your context allows borrowing.

Are there any ordering guarantees for the final result when dumping vec elements to a set in this way?

I ask because in some other programming languages, dumping vector or list elements into a set can result in a different ordering of the set elements for each individual run of the program (!).

In the case of dumping to set I would settle for a consistent ordering of the same input. But in general when finding unique elements of a vector, one might also want the ordering to match the order of appearance in the vector itself.

And there's the missing critical context.

If you want a Set with meaningful ordering guarantees, then you're probably looking for BTreeSet or some other Set implementation, rather than HashSet.

2 Likes

HashSet is not ordered, but you can use IndexSet.

1 Like

No, and what's more, the default hasher for HashSet (and HashMap) is intentionally randomized to prevent attacks. If you need a particular order based on the keys, use BTreeSet, and if you need insertion order, use the linked-hash-map crate.

3 Likes

Well, it's not my original question. But it seemed a relevant point to cover in the discussion :slight_smile:

Thanks to everyone who provided answers!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.