Menu
CoddyTech

セットとメンバーシップ

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

C++ の std::set は順序付けされていますが、C# の HashSet<T> はソート済みコンテナーではありません。どちらも一意性を保証しますが、順序が契約の一部である場合、移植時にはレポートを明示的にソートするか、SortedSet を選ぶ必要があります。

HashSet<T> は一意性と高速な要素の存在確認を実現します。ソートされたシーケンスではなく、列挙順をレポートの基準にしてはいけません。比較子によって文字列の等価性が決まります。セットの要素の存在確認とシーケンスのインデックスは、異なる問いに答えるものです。

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() {
set<string> seen{"a","a","b"};
cout << (seen.count("b") ? "yes" : "no") << "\n";
}

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

var seen = new HashSet<string> { "a", "a", "b" };
Console.WriteLine(seen.Contains("b") ? "yes" : "no");

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

リファレンス出力:

yes

C# の出力:

yes
challenge icon

チャレンジ

簡単

カンマ区切りの空でない単語のリストに含まれる、大文字と小文字を区別した異なる単語の数を返してください。空行は単語がないことを意味します。

編集可能な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 result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon腕試し

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

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

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