collections - 迭代元组中集合中的已排序元素

标签 collections rust iteration

我正在尝试以 2 个或更多元组的形式遍历集合中已排序的元素。

如果我有一个Vec,我可以调用

for window in my_vec.windows(2) {
    // do something with window
}

但是 Vec 不是隐式排序的,如果有的话就太好了。我尝试使用 BTreeSet 而不是 Vec,但我似乎无法在其上调用 windows

尝试调用时

for window in tree_set.iter().windows(2) {
    // do something with window
}

我得到了错误

no method named `windows` found for type `std::collections::btree_set::Iter<'_, Card>` in the current scope

最佳答案

Itertools 提供了 tuple_windows方法:

extern crate itertools;

use itertools::Itertools;
use std::collections::BTreeSet;

fn main() {
    let items: BTreeSet<_> = vec![1, 3, 2].into_iter().collect();

    for (a, b) in items.iter().tuple_windows() {
        println!("{} < {}", a, b);
    }
}

请注意,windows切片 上的方法,而不是迭代器上的方法,它返回原始切片的子切片的迭代器。 BTreeMap 可能无法提供相同的迭代器接口(interface),因为它不是建立在连续的数据 block 之上;将有一些值在内存中不会紧随后续值。

关于collections - 迭代元组中集合中的已排序元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290104/

相关文章:

rust - 如何使用new_type!宏来为氧化钠PublicKey和SecretKey设置更通用的类型?

Excel VBA : Is there a way to iterate through characters in a specific range?

java - Java泛型映射键值键入

rust - 如何将 i32 数字的 Vec<> 加入字符串?

rust - 如何从 &self 生成 &mut self?

iteration - 众包和迭代开发策略

c - 使用加法进行阶乘

collections - AutoMapper 和接口(interface)类型的集合

Java - 如何检查两个 ArrayList 是否是唯一对象(即使它们具有相同的值)?