2026-09-15
count_word.cpp
#include <iostream>
#include <map>
#include <string>
void count_word(std::map<std::string, int>& counts, const std::string& word) {
// write this: if word is new, register it with count 1 and
// print "new: word"; otherwise increment its count
}
count_wordを実装してください。ただしmapの探索は1回だけにし、途中で使う変数はif文の外へ漏らさないこと。
Reference
void count_word(std::map<std::string, int>& counts, const std::string& word) {
if (auto [it, inserted] = counts.try_emplace(word, 1); inserted)
std::cout << "new: " << word << '\n';
else
++it->second;
}
C++17からはif (初期化文; 条件)と書け、初期化文で宣言した変数はif文全体、つまりelse側でも使えて、文の外には漏れません。try_emplaceは「挿入を試みた位置」と「挿入したか」の組を返すので、構造化束縛で受ければ探索1回で両方の分岐を書けます。これは参考実装であり、唯一の正解ではありません。