2016-12-22 129 views
3

我正在嘗試迭代2個或更多元組中的集合中的排序元素。遍歷集合中的元組中的排序元素

如果我有一個Vec,我可以打電話給

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

Vec s的不隱式排序,這將是非常不錯的。我嘗試使用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 

回答

5

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是我通過,不在迭代器上,它返回原始片的子片的迭代器。 A BTreeMap大概不能提供相同的迭代器接口,因爲它不是建立在連續的數據塊之上的;將會有一些值不會立即存儲在隨後的值中。