マップと検索
Coddyの「Swift開発者のためのC++」コースのレッスン 14/48。
SwiftのDictionaryではキーの順序は定義されておらず、添字アクセスは挿入を行わずにOptionalを返します。また、d[key, default: 0]も、そこを通じて代入しない限り読み取りのみを行います。C++のstd::mapはキーをソートします。添字アクセスは、キーが存在しない場合にデフォルト値を挿入します。findとcountは挿入を行わずに検索します。
Swift
let counts = ["pens": 0]
print(counts["pads"] ?? 0, counts["pads", default: 0])
print(counts.count)
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
std::map<std::string,int> m{{"oak",4}};std::cout<<m.count("elm")<<" "<<m.size()<<"\n";
}
各プログラムを個別にトレースしてください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソース側とターゲット側の出力が一致するとは限りません。
チャレンジ
簡単入力:空白区切りの単語。単語の出現頻度を辞書順に並べ、スペースで結合した word:count を返します。単語がない場合は空にします。
exercise.hpp と exercise.cpp で宣言されたAPIを実装してください。両方のファイルを編集できます。公開シグネチャは変更しないでください。ロックされた main.cpp は標準入力を読み取り、APIを直接呼び出します。また、記載されている場合は公開APIの動作も個別に確認します。API内では出力せず、戻り値を返してください。整数の入力値と結果は符号付きintの範囲内です。特に記載がない限り、テキストはASCIIです。
自分で試してみよう
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<std::string>v;std::string w;while(in>>w)v.push_back(w);std::cout<<frequencies(v)<<"\n";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Swift開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ