相关疑难解决方法(0)

我可以有效地从HashSet中随机抽样吗?

我有一个std::collections::HashSet,我想要采样并删除一个均匀的随机元素.

目前,我正在做的是使用随机抽样索引rand.gen_range,然后迭代HashSet到该索引以获取元素.然后我删除所选元素.这有效,但效率不高.有没有一种有效的方法来随机抽样元素?

这是我的代码的简化版本:

use std::collections::HashSet;

extern crate rand;
use rand::thread_rng;
use rand::Rng;

let mut hash_set = HashSet::new();

// ... Fill up hash_set ...

let index = thread_rng().gen_range(0, hash_set.len());
let element = hash_set.iter().nth(index).unwrap().clone();
hash_set.remove(&element);

// ... Use element ...
Run Code Online (Sandbox Code Playgroud)

random hashset rust

6
推荐指数
3
解决办法
424
查看次数

标签 统计

hashset ×1

random ×1

rust ×1