英文:
Flatten a set of pairs in Rust
问题
我正在使用Rust中的HashSet<(usize, usize)>
处理整数对的集合,我的目标是计算一个包含这些整数对中出现的所有节点的HashSet<usize>
。从本质上讲,这是一个“展平”操作。
假设变量set: HashSet<(usize, usize)>
包含初始的整数对集合。我首次尝试计算展平版本如下:
let res: HashSet<usize> = set.iter().flatten().collect()
然而,我遇到了错误:“&(usize, usize)
不是一个迭代器,Iterator
特质未实现于&(usize, usize)
,&(usize, usize)
需要实现IntoIterator
特质以满足flatten
中的要求。”。
我认为问题在于迭代器是对引用的,所以我也尝试使用into_iter
,但我收到了相同的错误消息,这次是说“(usize, usize)
不是一个迭代器...”。
我确实有一段代码,使用for
循环和push
操作可以正常工作,但我希望以更函数式的方式使用flatten
来完成。
英文:
I am working with sets of pairs of integers in Rust using HashSet<(usize, usize)>
, and my goal is to compute a set HashSet<usize>
which contain all nodes appearing in those pairs. Essentially, this is a flatten
operation.
Let's suppose variable set: HashSet<(usize, usize)>
contains the initial set of pairs. My first attempt to compute the flattened version was:
let res: HashSet<usize> = set.iter().flatten().collect()
however I encounter the error: "&(usize, usize)
is not an iterator the trait Iterator
is not implemented for &(usize, usize)
required for &(usize, usize)
to implement IntoIterator
. Required by a bound in flatten
."
I thought the issue was that the iterator was over references so I also tried using into_iter
instead, but I get the same error message, this time saying "(usize, usize)
is not an iterator..."
I do have a piece of code that works fine using a for
loop and the push
operation, but I would like to do it in a more functional way with flatten
.
答案1
得分: 3
将元组简单地转换为一个可迭代的数组:
let res: HashSet<usize> = set.iter().flat_map(|&(a, b)| [a, b]).collect();
英文:
Simply convert the tuple to an array, which is iterable:
let res: HashSet<usize> = set.iter().flat_map(|&(a, b)| [a, b]).collect();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论