How to insert a value into a BTreeSet in Rust and then get an iterator beginning at its location?

夙愿已清 提交于 2019-12-12 18:35:12

问题


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.


回答1:


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);
    }    
}


来源:https://stackoverflow.com/questions/39121982/how-to-insert-a-value-into-a-btreeset-in-rust-and-then-get-an-iterator-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!