Reputation: 447
I have a BTreeSet
object and I want to convert it into a BTreeMap
with default indices (i.e., starting from 0 and incrementing). More precisely, given this:
let set = BTreeSet::from([0, 2, 4, 6, 8]);
I want to end up with BTreeMap<usize, usize>
that holds [(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)]
. I can do it with a loop for example as
let mut tree = BTreeMap::new();
for (i, v) in set.clone().into_iter().enumerate() {
tree.insert(i, v);
}
But is there any shortcut (i.e., one line code) that does the same?
Upvotes: 1
Views: 282
Reputation: 42272
But is there any shortcut (i.e., one line code) that does the same?
let map = set.iter().copied().enumerate().collect::<BTreeMap<_, _>>();
println!("{:?}", map);
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
tho note that this is a BTreeMap<usize, i32>
, because i32
is the default resolution for {integer}
literals if they're otherwise unconstrained, which is the case here.
Upvotes: 3