如何将值插入Rust中的BTreeSet,然后从其位置开始获取迭代器? [英] How to insert a value into a BTreeSet in Rust and then get an iterator beginning at its location?

查看:517
本文介绍了如何将值插入Rust中的BTreeSet,然后从其位置开始获取迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否遗漏了某些内容,或者无法从 BTreeSet 中新插入的值开始获取迭代器?



BTreeSet :: insert 只返回一个布尔值。为了比较,C ++中 std :: map insert 方法返回一对迭代器和一个布尔值。 / p>

可以查找新插入的元素并以这种方式获取迭代器,但效率很低。



这不是如何查找的副本并有效地插入HashMap?因为我需要一个指向新插入值位置的迭代器。我想获取前面和后面的值,如果存在的话。

解决方案

我不确定,但我' d猜测它归结为没有人需要它所以它没有被添加。



同时,你需要查阅最后一个如你所说,再次进入获取迭代器。这也提供了一个指定迭代器应该移动的方向的机会:

  use std ::收藏:: 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);
}
}


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.

解决方案

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

这篇关于如何将值插入Rust中的BTreeSet,然后从其位置开始获取迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆