In order to learn Rust, I'm rewriting some leetcode solution from C++ to Rust and on this way I struggle to understand how to perform some basic operations with iterators.
A particular good problem in this context is Data stream as disjoint intervals. The full implementation in C++ might be found elsewhere. To avoid going into particular algorithm details and concentrate on Rust syntax, I will post part of the C++ code which contains essential operations on C++ iterations which I struggle to translate into Rust:
map<int, int> m; // start to end, [x,y)
void addNum(int val) {
auto next = m.upper_bound(val); // seems that m.range(val+1..) might give what I need
if (next != begin(m)) { // begin(m) might be equivalent m.iter() but how to compare it with range is unclear
auto cur = prev(next); // haven't found prev method on range
int end = cur->second;
// adds to end of existing interval
if (val == cur->second) {
int start = cur->first;
end = val+1;
// merge two existing intervals
// ...
} else {
// ...
}
}
/// ...
}
The question is what are the equivalent operations on iterators in Rust? In particular, how to do upper_bound, check that what I've found is begin, do prev, get values/keys out of iterator.
range