問題一覧に戻る
中級データ構造
問題45: HashMapの応用

HashMapのentry APIはキーの存在確認と更新を効率的に行えます。or_insertはキーがない場合にデフォルト値を挿入し、and_modifyは既存値を変更します。これにより、単語カウントやスコア集計などの処理が簡潔に書けます。パフォーマンスも優れており、実用的なパターンです。

use std::collections::HashMap;

fn main() {
let mut word_count = HashMap::new();
let text = "hello world hello rust";

// 単語をカウント
for word in text.split_whitespace() {
let count = word_count.()
.();
*count += 1;
}

println!("Word count: {:?}", word_count);

// 更新パターン
let mut scores = HashMap::new();
scores.insert("Alice", 50);

// 既存値に加算
scores.entry("Alice")
.(10)
.(|v| *v += 10);

println!("Updated score: {:?}", scores);
}