Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Алгоритми та структури даних ЗПІ-91-20210115T104612Z-001 / Лекція 8. Хеш таблиці і словники.docx
Скачиваний:
27
Добавлен:
15.01.2021
Размер:
96.48 Кб
Скачать

Приклад 1

https://msdn.microsoft.com/ru-ru/library/ms132319(v=vs.110).aspx

У наступному прикладі створюється порожній об'єкт SortedList<TKey, TValue> рядків із строковими ключами і використовується метод Add для додавання декількох елементів. Як видно з прикладу, метод Add видає виключення ArgumentException при спробі додати дублікат ключа.

У прикладі для вибору значень використовується властивість Item (індексатор в C#); за відсутності вказаного ключа видається виключення KeyNotFoundException, причому значення, пов'язане з ключем, можна замінити.

У прикладі показано використання методу TryGetValue як ефективного способу вибору значень, якщо програма повинна часто намагатися використовувати значення ключів, які відсутні у відсортованому списку, а також демонструється застосування методу ContainsKey для перевірки існування ключа перед викликом методу Add.

У прикладі показано, як виконати перелічування ключів і значень у відсортованому списку і перелічування ключів і значень окремо, за допомогою Keys і Values.

І на закінчення в прикладі демонструється використання методу Remove.

using System;

using System.Collections.Generic;

public class Example

{

public static void Main()

{

// Create a new sorted list of strings, with string

// keys.

SortedList<string, string> openWith =

new SortedList<string, string>();

// Add some elements to the list. There are no

// duplicate keys, but some of the values are duplicates.

openWith.Add("txt", "notepad.exe");

openWith.Add("bmp", "paint.exe");

openWith.Add("dib", "paint.exe");

openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is

// already in the list.

try

{

openWith.Add("txt", "winword.exe");

}

catch (ArgumentException)

{

Console.WriteLine("An element with Key = \"txt\" already exists.");

}

// The Item property is another name for the indexer, so you

// can omit its name when accessing elements.

Console.WriteLine("For key = \"rtf\", value = {0}.",

openWith["rtf"]);

// The indexer can be used to change the value associated with a key.

openWith["rtf"] = "winword.exe";

Console.WriteLine("For key = \"rtf\", value = {0}.",

openWith["rtf"]);

// If a key does not exist, setting the indexer for that key

// adds a new key/value pair.

openWith["doc"] = "winword.exe";

// The indexer throws an exception if the requested key is

// not in the list.

try

{

Console.WriteLine("For key = \"tif\", value = {0}.",

openWith["tif"]);

}

catch (KeyNotFoundException)

{

Console.WriteLine("Key = \"tif\" is not found.");

}

// When a program often has to try keys that turn out not to

// be in the list, TryGetValue can be a more efficient

// way to retrieve values.

string value = "";

if (openWith.TryGetValue("tif", out value))

{

Console.WriteLine("For key = \"tif\", value = {0}.", value);

}

else

{

Console.WriteLine("Key = \"tif\" is not found.");

}

// ContainsKey can be used to test keys before inserting

// them.

if (!openWith.ContainsKey("ht"))

{

openWith.Add("ht", "hypertrm.exe");

Console.WriteLine("Value added for key = \"ht\": {0}",

openWith["ht"]);

}

// When you use foreach to enumerate list elements,

// the elements are retrieved as KeyValuePair objects.

Console.WriteLine();

foreach( KeyValuePair<string, string> kvp in openWith )

{

Console.WriteLine("Key = {0}, Value = {1}",

kvp.Key, kvp.Value);

}

// To get the values alone, use the Values property.

IList<string> ilistValues = openWith.Values;

// The elements of the list are strongly typed with the

// type that was specified for the SorteList values.

Console.WriteLine();

foreach( string s in ilistValues )

{

Console.WriteLine("Value = {0}", s);

}

// The Values property is an efficient way to retrieve

// values by index.

Console.WriteLine("\nIndexed retrieval using the Values " +

"property: Values[2] = {0}", openWith.Values[2]);

// To get the keys alone, use the Keys property.

IList<string> ilistKeys = openWith.Keys;

// The elements of the list are strongly typed with the

// type that was specified for the SortedList keys.

Console.WriteLine();

foreach( string s in ilistKeys )

{

Console.WriteLine("Key = {0}", s);

}

// The Keys property is an efficient way to retrieve

// keys by index.

Console.WriteLine("\nIndexed retrieval using the Keys " +

"property: Keys[2] = {0}", openWith.Keys[2]);

// Use the Remove method to remove a key/value pair.

Console.WriteLine("\nRemove(\"doc\")");

openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))

{

Console.WriteLine("Key \"doc\" is not found.");

}

}

}

/* This code example produces the following output:

An element with Key = "txt" already exists.

For key = "rtf", value = wordpad.exe.

For key = "rtf", value = winword.exe.

Key = "tif" is not found.

Key = "tif" is not found.

Value added for key = "ht": hypertrm.exe

Key = bmp, Value = paint.exe

Key = dib, Value = paint.exe

Key = doc, Value = winword.exe

Key = ht, Value = hypertrm.exe

Key = rtf, Value = winword.exe

Key = txt, Value = notepad.exe

Value = paint.exe

Value = paint.exe

Value = winword.exe

Value = hypertrm.exe

Value = winword.exe

Value = notepad.exe

Indexed retrieval using the Values property: Values[2] = winword.exe

Key = bmp

Key = dib

Key = doc

Key = ht

Key = rtf

Key = txt

Indexed retrieval using the Keys property: Keys[2] = doc

Remove("doc")

Key "doc" is not found.

*/

Елементами списку можуть бути об’єкти класів користувача.

Приклад 2

В прикладі створююється клас Student і колекція SortedList, впорядкована за зростанням рейтингу

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Lab17_OOP

{

class Student

{

public string StudentName {get;set;}

public string Group { get; set; }

public double Rating { get; set; }

public Student (string name,string group,double rating)

{

this.StudentName = name;

this.Group=group;

this.Rating=rating;

}

}

class Program

{

static void Main(string[] args)

{

SortedList<double, Student> List_SI_51=new SortedList<double, Student>();

//додавання в колекцію

List_SI_51.Add(76,new Student("Базяк","ПІ_51",76));

List_SI_51.Add(35, new Student("Кириченко", "ПІ_51", 35));

List_SI_21.Add(65, new Student("Мірошніченко", "ПІ_51", 65));

foreach (KeyValuePair<double, Student> kvp in List_SI_51)

{

Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value.StudentName);

}

Console.ReadKey();

}

}

}

8.2. Клас Dictionary<TKey, TValue> - словник

Клас Dictionary<TKey, TValue> дозволяє зберігати пари "ключ-значення" в колекції, як у словнику. Значення доступні у словнику за відповідними ключами.

Інтерфейси:

IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback

Конструктори

https://msdn.microsoft.com/ru-ru/library/xfhwa508(v=vs.110).aspx

Dictionary<TKey, TValue>()

Створює новий порожній екземпляр класу Dictionary<TKey, TValue>, що має початкову місткість за замовчанням і використовує компаратор за замовчанням, який перевіряє рівність для цього типу ключа.

Dictionary<TKey, TValue>(IDictionary<TKey, TValue>)

Створює новий екземпляр Dictionary<TKey, TValue>, який містить елементи, скопійовані з вказаного словника IDictionary<TKey, TValue>, і використовує для цього типу ключа компаратор за замовчанням

Dictionary<TKey, TValue>(IEqualityComparer<TKey>)

Створює новий порожній екземпляр класу Dictionary<TKey, TValue> з початковою місткістю за замовчанням, що використовує вказаний компаратор IEqualityComparer<T>.

Властивості

Comparer

Повертає компаратор IEqualityComparer<T>, використовуваний для встановлення рівності ключів словника.

Count

Повертає число пар "ключ-значення", що містяться в Dictionary<TKey, TValue>.

Item

Отримує або задає значення, пов'язане із заданим ключем.

Keys

Отримує колекцію, що містить ключі із Dictionary<TKey, TValue>.

Values

Отримує колекцію, що містить значення в об'єкті Dictionary<TKey, TValue>.

Методи

Add

Додає вказаний ключ і значення в словник Dictionary<TKey, TValue>

Clear

Видаляє усі ключі і значення із словника Dictionary<TKey, TValue>.

ContainsKey

Визначає, чи міститься вказаний ключ у словнику Dictionary<TKey, TValue>.

ContainsValue

Визначає, чи містить колекція Dictionary<TKey, TValue> вказане значення.

Equals(Object)

Визначає, чи рівний заданий об'єкт поточному об'єкту. (Успадковано від Object.)

Finalize

Дозволяє об'єкту спробувати звільнити ресурси і виконати інші операції очищення, перш ніж об'єкт буде знищено. (Успадковано від Object.)

GetEnumerator

Повертає нумератор, що здійснює перебір елементів словника Dictionary<TKey, TValue>.

GetHashCode

Грає роль хеш-функції для певного типу.(Успадковано від Object.)

GetType

Повертає об'єкт Type для поточного екземпляра. (Успадковано від Object.)

MemberwiseClone

Створює неповну копію поточного об'єкту Object. (Успадковано від Object.)

Remove

Видаляє значення з вказаним ключем із словника Dictionary<TKey, TValue>.

ToString

Повертає рядок, що представляє поточний об'єкт. (Успадковано від Object.)

TryGetValue

Набуває значення, пов'язаного з вказаним ключем.

Приклад 3.

https://msdn.microsoft.com/ru-ru/library/xfhwa508(v=vs.110).aspx

У наступному прикладі коду створюється порожній об'єкт Dictionary<TKey, TValue> рядків із строковими ключами і використовується метод Add для додавання декількох елементів. Як видно з прикладу, метод Add видає виключення ArgumentException при спробі додати дублікат ключа.

У прикладі для отримання значень використовується властивість Item (індексатор в C#); за відсутності вказаного ключа видається виключення KeyNotFoundException, причому значення, пов'язане з ключем, можна замінити.

У прикладі показано використання методу TryGetValue як ефективного способу вибору значень в програмі, що часто намагається використовувати значення ключів, відсутні в словнику, а також демонструється застосування методу ContainsKey для перевірки існування ключа перед викликом методу Add.

У прикладі показано, як виконати перебір ключів і значень в словнику і перебір ключів і значень окремо, використовуючи властивості Keys і Values.

І на закінчення в прикладі демонструється використання методу Remove.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Dictionary

{

class Program

{

public static void Main()

{

// Create a new dictionary of strings, with string keys.

//

Dictionary<string, string> openWith =

new Dictionary<string, string>();

// Add some elements to the dictionary. There are no

// duplicate keys, but some of the values are duplicates.

openWith.Add("txt", "notepad.exe");

openWith.Add("bmp", "paint.exe");

openWith.Add("dib", "paint.exe");

openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is

// already in the dictionary.

try

{

openWith.Add("txt", "winword.exe");

}

catch (ArgumentException)

{

Console.WriteLine("An element with Key = \"txt\" already exists.");

}

// The Item property is another name for the indexer, so you

// can omit its name when accessing elements.

Console.WriteLine("For key = \"rtf\", value = {0}.",

openWith["rtf"]);

// The indexer can be used to change the value associated

// with a key.

openWith["rtf"] = "winword.exe";

Console.WriteLine("For key = \"rtf\", value = {0}.",

openWith["rtf"]);

// If a key does not exist, setting the indexer for that key

// adds a new key/value pair.

openWith["doc"] = "winword.exe";

// The indexer throws an exception if the requested key is

// not in the dictionary.

try

{

Console.WriteLine("For key = \"tif\", value = {0}.",

openWith["tif"]);

}

catch (KeyNotFoundException)

{

Console.WriteLine("Key = \"tif\" is not found.");

}

// When a program often has to try keys that turn out not to

// be in the dictionary, TryGetValue can be a more efficient

// way to retrieve values.

string value = "";

if (openWith.TryGetValue("tif", out value))

{

Console.WriteLine("For key = \"tif\", value = {0}.", value);

}

else

{

Console.WriteLine("Key = \"tif\" is not found.");

}

// ContainsKey can be used to test keys before inserting

// them.

if (!openWith.ContainsKey("ht"))

{

openWith.Add("ht", "hypertrm.exe");

Console.WriteLine("Value added for key = \"ht\": {0}",

openWith["ht"]);

}

// When you use foreach to enumerate dictionary elements,

// the elements are retrieved as KeyValuePair objects.

Console.WriteLine();

foreach (KeyValuePair<string, string> kvp in openWith)

{

Console.WriteLine("Key = {0}, Value = {1}",

kvp.Key, kvp.Value);

}

// To get the values alone, use the Values property.

Dictionary<string, string>.ValueCollection valueColl =

openWith.Values;

// The elements of the ValueCollection are strongly typed

// with the type that was specified for dictionary values.

Console.WriteLine();

foreach (string s in valueColl)

{

Console.WriteLine("Value = {0}", s);

}

// To get the keys alone, use the Keys property.

Dictionary<string, string>.KeyCollection keyColl =

openWith.Keys;

// The elements of the KeyCollection are strongly typed

// with the type that was specified for dictionary keys.

Console.WriteLine();

foreach (string s in keyColl)

{

Console.WriteLine("Key = {0}", s);

}

// Use the Remove method to remove a key/value pair.

Console.WriteLine("\nRemove(\"doc\")");

openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))

{

Console.WriteLine("Key \"doc\" is not found.");

}

Console.ReadKey();

}

}

}

Ще один приклад

Приклад 4. В прикладі демонструється робота з колекцією Dictionary<TKey, TValue>

namespace Dictionary

{

class UserInfo

{

// Метод, реализующий словарь

public static Dictionary<int, string> MyDic(int i)

{

Dictionary<int, string> dic = new Dictionary<int, string>();

Console.WriteLine("Введите имя сотрудника: \n");

string s;

for (int j = 0; j < i; j++)

{

Console.Write("Name{0} --> ", j);

s = Console.ReadLine();

dic.Add(j, s);

Console.Clear();

}

return dic;

}

}

class Program

{

static void Main(string[] args)

{

Console.Write("Сколько сотрудников добавить? ");

try

{

int i = int.Parse(Console.ReadLine());

Dictionary<int, string> dic = UserInfo.MyDic(i);

// Получить коллекцию ключей

ICollection<int> keys = dic.Keys;

Console.WriteLine("База данных содержит: ");

foreach (int j in keys)

Console.WriteLine("ID -> {0} Name -> {1}",j,dic[j]);

}

catch (FormatException)

{

Console.WriteLine("Неверный ввод");

}

Console.ReadLine();

}

}

}

Практичне застосування словника в задачах аналізу тексту. Потрібно створити словник усіх слів тексту і кількості появи кожного слова у тексті.

У якості ключів будемо використовувати слова, а у якості значення – кількість повторень слова у тексті.