1 / 10

Последовательные коллекции

Последовательные коллекции. 2014. Коллекция List<T>. class Point { public int X, Y; }. List < Point > l = new List < Point > { new Point { X = 3, Y = 3 }, new Point { X = 2, Y = 4 }, }; l.Sort (); foreach ( var p in l) Console .WriteLine ( p.X );.

gerik
Download Presentation

Последовательные коллекции

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Последовательные коллекции 2014

  2. Коллекция List<T> classPoint { publicint X, Y; } List<Point> l = newList<Point> { newPoint { X = 3, Y = 3 }, newPoint { X = 2, Y = 4 }, }; l.Sort(); foreach (var p in l) Console.WriteLine(p.X); Сокращенный синтаксис инициализации коллекции

  3. Методы List<T> • intIndexOf(T item); • void Insert(int index, T item); • bool Remove(T item); • voidRemoveAt(int index); • T[] ToArray(); void Add(T item); voidAddRange(otherCollection); intBinarySearch(T item); void Clear(); bool Contains(T item); var lst1 = newList<int> { 5, 3, 4 }; var lst2 = newList<int> { 4, 6, 8 }; inti = 0; while (i < lst1.Count) { if (lst2.Contains(lst1[i])) lst1.RemoveAt(i); else i++; } foreach (var x in lst1) Console.Write(x + " ");

  4. Сортировка коллекции collection.Sort(); Элементы коллекции можно сравнивать, если тип T реализует интерфейс IComparable или IComparable<T>. classPoint: IComparable { publicint X, Y; publicintCompareTo(objectobj) { Point p = (Point)obj; return X - p.X; } } classPoint : IComparable<Point> { publicint X, Y; publicintCompareTo(Point p) { return X - p.X; } }

  5. IComparer<T> • collection.Sort(comparer); Правило сравнениязадается при помощи объекта с интерфейсом IComparer<T>. classMyComparer : IComparer<Point> { publicint Compare(Point a, Point b) { returna.X - b.X; } } Сортировка с компаратором: list.Sort(newMyComparer());

  6. Прохождение коллекции Благодаря индексатору коллекцию можно пройти при помощи цикла for. Благодаря перечислителю коллекцию можно пройти при помощи цикла foreach. Перечислитель – это тип, реализующий интерфейс IEnumerator. publicinterfaceIEnumerator { object Current { get; } boolMoveNext(); void Reset(); }

  7. Foreachпо Вектору Vector<char> vector = newVector<char>(); • vector.Add('a'); • vector.Add('b'); • vector.Add('c'); • foreach (char c in vector) { Console.WriteLine(c); } Чтобы это работало, нужно: объявить тип перечислителя для вектора; реализовать в Векторе интерфейс IEnumerableили IEnumerable<T>

  8. Перечислитель для Вектора publicclassVectorEnumerator<T> : IEnumerator<T> { Vector<T> vector; int pos = -1; publicVectorEnumerator(Vector<T> v) { vector = v; } public T Current { get { returnvector.array[pos]; } } publicvoid Dispose() { } objectIEnumerator.Current { get { thrownewNotImplementedException(); } } publicboolMoveNext() { return ++pos < vector.Count; } publicvoid Reset(){ pos = -1; } }

  9. Как устроен цикл foreach foreach(int item in v) Console.Write(item); for(IEnumerator<int> e = v.GetEnumerator(); e.MoveNext();) { int item = e.Current; Console.Write(item); }

  10. Самостоятельно Даны две коллекции IList. Объявите метод, которыйвозвращаеттретьюколлекцию – пересечениедвухзаданных. Соедините две упорядоченных коллекции в третью, тоже упорядоченную. Сделайте это за время O(n), где n – число элементов в коллекциях. Унаследуйте коллекцию List<T> и перекройте метод ToString(), чтобы распечатать коллекцию в строку. Объявите такой перечислитель вектора, который бы проходил вектор в обратном порядке.

More Related