Caution
お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。
Iterator::collect() / count() / sum()
Rustのイテレータの終端操作には、要素を集める『collect()』、件数を数える『count()』、合計を求める『sum()』、積を求める『product()』などがあります。終端操作を呼ぶとイテレータが消費されます。
構文
// collect(): イテレータの要素をコレクションに集めます。 let v: Vec<i32> = (1..=5).collect(); let s: String = vec!['a', 'b', 'c'].into_iter().collect(); // count(): 要素の数を数えます。 let n = (1..=10).filter(|x| x % 2 == 0).count(); // 5 // sum(): 要素の合計を求めます(型注釈が必要な場合があります)。 let total: i32 = vec![1, 2, 3, 4, 5].iter().sum(); // 15 // product(): 要素の積を求めます。 let prod: i32 = vec![1, 2, 3, 4, 5].iter().product(); // 120 // min() / max(): 最小値・最大値を求めます(Option を返します)。 let min = vec![3, 1, 4, 1, 5].iter().min(); // Some(1) let max = vec![3, 1, 4, 1, 5].iter().max(); // Some(5)
終端操作一覧
| メソッド | 概要 |
|---|---|
| iter.collect::<型>() | イテレータをVec・HashMapなどのコレクションに変換します。 |
| iter.count() | 要素数をusize型で返します。 |
| iter.sum::<T>() | 全要素の合計を返します(Sumトレイトが必要)。 |
| iter.product::<T>() | 全要素の積を返します(Productトレイトが必要)。 |
| iter.min() | 最小値をOption<&T>で返します。 |
| iter.max() | 最大値をOption<&T>で返します。 |
| iter.min_by_key(|x| ...) | キー関数が最小の要素をOptionで返します。 |
| iter.max_by_key(|x| ...) | キー関数が最大の要素をOptionで返します。 |
| iter.last() | 最後の要素をOptionで返します。 |
| iter.nth(n) | n番目の要素をOptionで返します(0始まり)。 |
| iter.for_each(|x| ...) | 各要素に処理を適用します(戻り値は不要な場合のfor文代替)。 |
サンプルコード
use std::collections::HashMap;
fn main() {
// collect(): Vec に集めます。
let v: Vec<i32> = (1..=5).collect();
println!("collect Vec: {:?}", v);
// collect(): HashMapに集めます。
let map: HashMap<i32, i32> = (1..=5).map(|x| (x, x * x)).collect();
println!("collect HashMap: {:?}", map);
// collect(): Stringに集めます。
let s: String = vec!['R', 'u', 's', 't'].into_iter().collect();
println!("collect String: {}", s);
// count(): 条件を満たす要素の数を数えます。
let even_count = (1..=20).filter(|x| x % 2 == 0).count();
println!("1〜20の偶数の個数: {}", even_count);
// sum(): 合計を求めます。
let total: i32 = (1..=100).sum();
println!("1〜100の合計: {}", total);
let float_sum: f64 = vec![1.1, 2.2, 3.3].iter().sum();
println!("float sum: {:.1}", float_sum);
// product(): 階乗を計算します(5! = 120)。
let factorial: u64 = (1..=5).product();
println!("5! = {}", factorial);
// min() / max() です。
let data = vec![5, 3, 8, 1, 9, 2, 7];
println!("min: {:?}", data.iter().min()); // Some(1)
println!("max: {:?}", data.iter().max()); // Some(9)
// min_by_key() / max_by_key() で構造体の特定フィールドで比較します。
let words = vec!["hello", "hi", "hey", "world"];
let shortest = words.iter().min_by_key(|w| w.len());
let longest = words.iter().max_by_key(|w| w.len());
println!("最短: {:?}", shortest); // Some("hi")
println!("最長: {:?}", longest); // Some("hello") か "world"
// for_each(): 各要素に処理を適用します。
(1..=3).for_each(|x| println!("for_each: {}", x));
}
実行結果
collect Vec: [1, 2, 3, 4, 5]
collect HashMap: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
collect String: Rust
1〜20の偶数の個数: 10
1〜100の合計: 5050
float sum: 6.6
5! = 120
min: Some(1)
max: Some(9)
最短: Some("hi")
最長: Some("hello")
for_each: 1
for_each: 2
for_each: 3
概要
『collect()』は型推論が使えるため、多くの場合は変数の型注釈(': Vec<i32>')で型を指定します。ターボフィッシュ構文('.collect::<Vec<i32>>()')でも指定できます。
『sum()』と『product()』は型注釈が必要な場合があります。イテレータが『&i32』を返す場合でも『sum::<i32>()』や変数の型注釈で解決できます。
変換・絞り込みのアダプタは『Iterator::map() / filter()』を、畳み込みと検索は『Iterator::fold() / any() / all() / find()』を参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。