在Rust中展平一组成对的元素。

huangapple go评论52阅读模式
英文:

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&lt;(usize, usize)&gt;, and my goal is to compute a set HashSet&lt;usize&gt; which contain all nodes appearing in those pairs. Essentially, this is a flatten operation.

Let's suppose variable set: HashSet&lt;(usize, usize)&gt; contains the initial set of pairs. My first attempt to compute the flattened version was:

let res: HashSet&lt;usize&gt; = set.iter().flatten().collect()

however I encounter the error: "&amp;(usize, usize) is not an iterator the trait Iterator is not implemented for &amp;(usize, usize) required for &amp;(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&lt;usize&gt; = set.iter().flat_map(|&amp;(a, b)| [a, b]).collect();

huangapple
  • 本文由 发表于 2023年2月14日 20:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定