< 返回版块

Louys·Miaoa 豆沙饼 发表于 2022-09-22 08:54

想问一下 一个Vec 怎么转成 一个HashSet, 使用 HashSet::from() 和 HashSet::from_iter(),

已提供了playground 代码, 但是不会写.


Ext Link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=use%20std%3A%3Acollections%3A%3AHashSet%3B%0D%0Afn%20main()%20%7B%0D%0A%20%20%20%20let%20v%20%3D%20vec!%5B1%2C%202%2C%203%2C%204%5D%3B%0D%0A%20%20%20%20let%20v2%20%3D%20vec!%5B1%2C%202%2C%203%2C%204%5D%3B%0D%0A%20%20%20%20let%20set%3AHashSet%3Ci32%3E%20%3D%20HashSet%3A%3Afrom_iter%3A%3A%3Ci32%3E(v.iter())%3B%0D%0A%20%20%20%20let%20set%20%3D%20HashSet%3A%3Afrom(v2)%3B%0D%0A%7D

评论区

写评论
作者 Louys·Miaoa 豆沙饼 2022-09-25 22:36

大哥, 感谢您. 您认真看了我的问题哈. 真的非常感谢

--
👇
furoxr:

use std::collections::HashSet;
fn main() {
    let v = vec![1, 2, 3, 4];
    let v2 = vec![1, 2, 3, 4];
    let _set: HashSet<i32> = HashSet::from_iter(v);
    let array: [i32;4] = v2.try_into().unwrap();
    let _set = HashSet::from(array);
}
furoxr 2022-09-22 09:41
use std::collections::HashSet;
fn main() {
    let v = vec![1, 2, 3, 4];
    let v2 = vec![1, 2, 3, 4];
    let _set: HashSet<i32> = HashSet::from_iter(v);
    let array: [i32;4] = v2.try_into().unwrap();
    let _set = HashSet::from(array);
}
作者 Louys·Miaoa 豆沙饼 2022-09-22 09:32

感谢感谢

--
👇
我心飞翔: let v1 = vec![1, 2, 3, 4]; let v2 = vec![1, 2, 3, 4]; let set1: HashSet = v1.iter().map(|x| *x).collect(); let set2: HashSet = v2.iter().map(|x| *x).collect();

作者 Louys·Miaoa 豆沙饼 2022-09-22 09:31

感谢感谢

--
👇
ezlearning: let v = vec![1, 2, 3, 4]; let set: HashSet = v.into_iter().collect::<HashSet>();

c5soft 2022-09-22 09:30
use std::collections::HashSet;
fn main() {
    let v = vec![1, 2, 3, 4];
    let set:HashSet<i32> = HashSet::from_iter(v.into_iter());
    println!("{:?}",set);
}
ezlearning 2022-09-22 09:20
let v = vec![1, 2, 3, 4];
let set: HashSet<i32> = v.into_iter().collect::<HashSet<i32>>();
我心飞翔 2022-09-22 09:15
let v1 = vec![1, 2, 3, 4];
let v2 = vec![1, 2, 3, 4];
let set1: HashSet<i32> = v1.iter().map(|x| *x).collect();
let set2: HashSet<i32> = v2.iter().map(|x| *x).collect();
1 共 7 条评论, 1 页