This is a "which data structure will work" question. I have a situation where I need to be able to insert an element by a numeric key, and then, grab a slice starting at a numeric key to the end.
An pseudo code example:
let data = [
1 = String::from("One"),
3 = String::from("Three"),
12 = String::from("Twelve"),
62 = String::from("Sixty Two"),
91 = String::from("Ninety One"),
]
Where I could insert a new item, say 73, and it would be inserted between 62 and 91. Then, I can take a slice and grab a vector or other iterable collection from 12+.
let twelve_plus = &[12..];
Which would be a vector with three elements.
My first thought was to use vectors. And, I was able to insert into an empty vector
let mut data = vec![];
data[1] = String::from("One");
data[3] = String::from("Three");
// etc
But, I wasn't able to use the vector. I couldn't iterate or grab a range because I got a panic
thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 1'
Which makes sense to me. I have considered the BTreeMap
, which will allow for ordering and iteration, but I don't know how to get a slice from that.
The only other solution I can think of is to wrap the vector in a type, and implement my own insert method, which inserts an optional value of None
as needed. So, the first insert of 1
would actually insert an empty value into 0
and then a good value into 1
. This is acceptable, but I was hoping for a more elegant solution.
Am I missing something obvious? Thanks for the help!