Menu
CoddyTech

ディクショナリと存在しないキー

Coddyの「C++開発者のためのC#」コースのレッスン 18/48。

C++のmapのoperator[]は存在しないキーにデフォルト値を挿入しますが、C#のDictionaryのインデックス指定では例外がスローされます。C++のfindは挿入を避け、概念的にはTryGetValueに相当します。探索のための検索を、誤って書き込みや例外につながる操作に変えないでください。

Dictionary<TKey,TValue>は、型付きのキーと値を関連付けます。インデクサーで存在しないキーを読み取ると例外がスローされます。TryGetValueを使うと、キーの存在と格納された値を個別に確認できます。大文字と小文字を区別する安定した機械用キーには、StringComparer.Ordinalを選びましょう。toStringという名前のキーは、単なるキーです。

C++の参照コード

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
map<string,int> values;
auto it=values.find("missing");
cout << (it==values.end()?0:it->second) << "\n";
}

Main内のC#ステートメント

var values = new Dictionary<string,int>();
int count;
Console.WriteLine(values.TryGetValue("missing", out count) ? count : 0);

これらは要点を絞った学習用抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言とステートメントが示されています。

参照出力:

0

C#の出力:

0
challenge icon

チャレンジ

簡単

カンマで区切られた空でないASCII単語を読み込みます。単語がない場合は空行を読み込み、その後に検索キーを読み込みます。キーと大文字・小文字を区別して完全一致する出現回数を数えます。キーが見つからない場合は0を返します。

ロックされていないC#ファイルを編集してください。表示されているロック済みのMain.csは説明されている行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを検証して、最後に改行を1つ付けて結果を出力します。宣言済みのAPIはそのままにしてください。2つ目のMainを追加したり、診断出力を表示したりしないでください。

自分で試してみよう

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Words(input[0]); string before0=Snapshot(a0);
var a1 = input[1]; string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ