I have a Vec<MyType>
. For my algorithm, I need MyType
elements sorted according to different criteria. One is the insertion order, for which Vec<MyType>
is used directly: I just index the element in the vector.
I also need to have MyType
elements ordered by two other criteria.
In C++, I would simply create a std::set<size_t>
, insert the indices of the elements in the Vec<MyType>
, and provide a comparator object with a pointer/reference to the vector, so I could get the elements from the indices and compare them however I like.
According to this answer, I can't do that with Rust's BTreeSet
, and I must implement trait Ord
. But I can't implement Ord
unless I also store a reference to Vec<MyType>
in every element of the BTreeSet
. I don't want to copy the elements because they are big and complex objects.
I also tried using Vec<Box<MyType>>
and BTreeSet<&MyType>
, but then I found that I can't have both inside the same struct, as a struct can't store a reference using its own lifetime.
So, is there a Rust idiomatic and safe way of doing this (preferably without using Rc<>
, as I know my elements are never removed)?
struct MyType {
/// Ordered by insertion order.
basis: Vec<Box /* ?? maybe ?? */<MyType>>;
/// Alternative ordering for basis.
alt1_ordering: BTreeSet</*???*/>;
/// Other alternative ordering for basis.
alt2_orderign: BTreeSet</*???*/>;
}