3

Am I missing something, or is there no way to get an iterator beginning at the newly-inserted value in a BTreeSet?

BTreeSet::insert just returns a boolean. For comparison, the insert method for std::map in C++ returns a pair of an iterator and a boolean.

It is possible to look up the newly-inserted element and get the iterator that way, but that's inefficient.

This isn't a duplicate of How to lookup from and insert into a HashMap efficiently? as I need to get an iterator pointing to the location of the newly inserted value. I want to obtain the preceding and following values, if these exist.

Community
  • 1
  • 1
foldl
  • 725
  • 1
  • 7
  • 23

1 Answers1

0

I don't know for sure, but I'd guess that it boils down to the fact that no one has needed it so it hasn't been added.

In the meantime, you will need to look up the last entry again to get an iterator, as you mention. This also gives an opportunity to specify the direction that the iterator should travel:

use std::collections::BTreeSet;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(1);
    set.insert(2);
    set.insert(3);

    set.insert(0);
    for i in set.range(0..) {
        println!("{}", i);
    }    
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366