Một số cấu trúc dữ liệu Stack Stack là một cấu trúc theo kiểu LIFO Last In First Out, phần tử vào sau cùng sẽ được lấy ra trước.. Một số cấu trúc dữ liệu Stack – Lưu ý Khi 1 phần tử đư
Trang 1Chương 3: Cấu trúc dữ liệu trong C#
Trang 2Cấu trúc dữ liệu trong C#
Trang 3Lâp trình tổng quát trong C#
3
Trang 4Giới thiệu LTTQ Giới thiệu
Trang 5Giới thiệu LTTQ Generic trong NET 2.0
biến rõ ràng trước khi sử dụng.
mà không cần phải xác định đó là kiểu dữ li u gì Tuy nhiên khi câu truc dữ li u này được sử dụng, trình biên dịch phải ê ê đảm bảo răng kiểu dữ li u ê được sử dụng với nó là kiểu an toàn Generic cũng tương đương vơi Template trong C++ tuy nhiên
5
Trang 6Giới thiệu LTTQ Ý nghĩa
Lập trình tổng quát cho phép bạn trì hoãn kiểu dữ liệu với các thành phần của lớp hay phương thức cho đến khi nó thực
sự được sử dụng trong chương trình Nói cách khác, Generics cho phép bạn viết lớp hay phương thức có thể làm việc với bất kỳ kiểu dữ liệu nào.
Khi trình biên dịch gọi đến constructor hoặc phương thức của lớp, nó sẽ tự động sinh code để xử lý cho kiểu dữ liệu cho phù hợp.
Trang 8//declaring an int array
MyGenericArray <int> intArray = new
Trang 9//declaring a character array
MyGenericArray <char> charArray = new
Trang 10Giới thiệu LTTQ Features of Generics
Using generics is a technique that enriches your programs in the following ways:
It helps you to maximize code reuse, type safety, and performance.
You can create generic collection classes The NET Framework class library contains several new generic collection classes in
the System.Collections.Generic namespace You may use these generic collection classes instead of the collection classes in the System.Collectionsnamespace.
You can create your own generic interfaces, classes, methods, events and delegates.
You may create generic classes constrained to enable access to methods on particular data types.
You may get information on the types used in a generic data type at run-time by means of reflection.
Trang 11Giới thiệu LTTQ Generic Class
Generic classes have type parameters Separate classes, each with a different field type in them, can be
replaced with a single generic class The generic class introduces a type parameter This becomes part of the class definition itself.
11
Trang 12Giới thiệu LTTQ Generic Class - Example
// Use the generic type Test with an int type parameter.
Test < int > test1 = new Test < int >(5);
// Call the Write method.
test1.Write();
// Use the generic type Test with a string type parameter.
Test < string > test2 = new Test < string >( "cat" );
test2.Write();
} }
Trang 13Giới thiệu LTTQ Generic methods
In the previous example, we have used a generic class; we can declare a generic method with a type parameter
A generic method is a template of a method that takes a number of type parameters
Có thể khai báo phương thức tổng quát trong cả lớp non-generic và lớp generic.
13
Trang 14Giới thiệu LTTQ Generic methods - Example
Console WriteLine( "a = {0} , b = {1} " , a, b);
Console WriteLine( "Char values before calling swap:" );
Console WriteLine( "c = {0} , d = {1} " , c, d);
Swap< int >( ref a, ref b);
Swap< char >( ref c, ref d);
Console WriteLine( "a = {0} , b = {1} " , a, b);
Console WriteLine( "c = {0} , d = {1} " , c, d);
} }
Trang 15Giới thiệu LTTQ Generic struct
Generic struct rất giống với generic class.
Cụ thể ta xem xét qua ví dụ sau:
internal struct GenericStruct <T>
get { return _Data; }
set { _Data = value ; }
GenericStruct < int > IntData = new GenericStruct < int >(10); GenericStruct < string > StringData = new
GenericStruct < string >( "str" );
Console WriteLine( "IntData = {0} " , IntData.Data);
Console WriteLine( "StringData = {0} " , StringData.Data); }
}
Trang 16Giới thiệu LTTQ Constraints
Ràng bu c tham sô ô
Generic cho ta viết m t lớp mà không cần xác định kiểu dữ li u cụ thể, nhưng vân cho phep ngươi sử dụng lớp đó chi ra kiểu dữ li u cụ thể se ô ê ê sử dụng Điều này tạo ra sư linh hoạt băng cách thay thế m t sô ô ràng bu c về kiểu ô mà có thể được sử dụng trong các tham sô.
public static T Max<T> (T op1, T op2) where T : IComparable{
if (op1.CompareTo(op2) < 0)
return op1;
return op2;
}
Trong ví dụ đã chi ra ràng bu c mà kiểu được sử dụng cho kiểu tham sô phải thưc thi giao di n IComparable. ô ê
Trang 17Giới thiệu LTTQ Constraints
where T : struct – T là câu truc (value type) where T : class – T là lớp (reference type) where T : new() - yêu cầu T phải có một constructor không tham sô Khi có nhiều ràng buộc thì new() phải ở cuôi cùng where T : class_name - tên lớp mà tham sô T phải thừa kế
17
Trang 18Giới thiệu LTTQ Constraints
where T : class The type argument must be a reference type, including any class, interface, delegate, or array type.
where T : new() The type argument must have a public parameterless constructor When used in conjunction with other constraints, the new() constraint must be
specified last
where T : <base class name> The type argument must be or derive from the specified base class.
where T : <interface name> The type argument must be or implement the specified interface Multiple interface constraints can be specified The constraining interface can also
be generic.
where T : U The type argument supplied for T must be or derive from the argument supplied for U This is called a naked type constraint.
Trang 19Giới thiệu LTTQ Constraints
where S: B {
}
class E<T>: D where T: class{
}
class F<T>: D where T: struct{
}
class G<T>: D where T: new(){
}
19
Trang 21Một số cấu trúc dữ liệu Stack
Stack là một cấu trúc theo kiểu LIFO (Last In First Out), phần tử vào sau cùng sẽ được lấy ra trước.
Hai thao tác cơ bản trên Stack
Chèn phần tử: Luôn chèn vào đỉnh Stack (push)
Lấy ra phần tử: Luôn lấy ra từ đỉnh Stack (pop)
Lớp Stack thuộc namespace System.Collections, biểu diễn ngăn xếp (LIFO) các đối tượng non – generic Để sử dụng kiểu generic dùng System.Collections.Generic.Stack<T>.
Lớp Stack hiện thực các giao diện ICollection, IEnumerable, ICloneable.
21
Trang 22Một số cấu trúc dữ liệu Stack - Example
class Program
{ static void Main( string [] args) {
Trang 23Một số cấu trúc dữ liệu Stack – Lưu ý
Khi 1 phần tử được thêm vào (Push), capacity tự động tăng, và tổ chức lại bộ nhớ Nếu Count< Capacity thì Push có số phép toán
là O(1), ngược lại là O(n) (n = Count) Pop có số phép toán là O(1).
Stack cho phép chèn phần tử null, hoặc các phần tử có giá trị bằng nhau.
23
Trang 24Một số cấu trúc dữ liệu Stack class in C#
Stack() Khởi tạo Stack trông, capacity ban đầu mặc định.
Stack(ICollection) Khởi tạo Stack chứa các phần tử copy từ một tập hợp (mảng), capacity ban đầu băng sô phần tử
được copy.
Stack(Int32) Khởi tạo Stack trông, capacity ban đầu băng giá trị truyền vào (Dùng Contructor này tôt nhât)
WHY?
Trang 25Một số cấu trúc dữ liệu Stack class in C#
Clear Removes tât cả các đôi tượng trong Stack.
Clone Tạo bản sao của Stack.
Contains Xác định xem phần tử có trong Stack.
CopyTo Copy stack ra mảng 1 chiều, bắt đầu từ vị trí chi định ( Nếu mảng chứa các KDL khác nhau ?)
Peek Trả về đôi tượng trên đinh Stack không remove nó khỏi stack.
Pop Remove và trả về đôi tượng trên đinh stack.
Push Chèn một đôi tượng vào đinh stack ToArray Copy stack ra một mảng mới.
Trang 26Một số cấu trúc dữ liệu Queue
Queue (Hàng đợi) là cấu trúc theo kiểu FIFO (First In First Out), phần tử vào trước sẽ được lấy ra trước.
Hai thao tác cơ bản trên hàng đợi
Chèn phần tử: Luôn chèn vào cuối hàng đợi (enqueue)
Lấy ra phần tử: Lấy ra từ đầu hàng đợi (dequeue)
Lớp Queue thuộc namespace System.Collections, biểu diễn ngăn xếp (FIFO) các đối tượng non – generic Để sử dụng kiểu generic dùng System.Collections.Generic.Queue<T>.
Lớp Queue hiện thực các giao diện ICollection, IEnumerable, ICloneable.
Trang 27Một số cấu trúc dữ liệu Queue - Example
int[] a = { 10, 20, 30, 10 };
Queue q = new Queue(a);
q.Enqueue(22);
while (q.Count > 0) Console.WriteLine(q.Dequeue());
Console.ReadLine();
}}
27
Trang 28Một số cấu trúc dữ liệu Queue – Lưu ý
capacity của queue là số phần tử nó có thể chứa, count là số các phần tử hiện có trong queue Khi Insert 1 phần tử vào, capacity
tự động tăng, capacity có thể giảm khi gọi phương thức TrimToSize().
growth factor là hệ số nhân của capacity khi tăng kích thước, giá trị mặc định là 2.0 Capacity tăng tối thiểu là 4 ?
Queue cho phép chèn giá trị null, và các phần tử có giá trị bằng nhau.
Trang 29Một số cấu trúc dữ liệu Queue – Constructor
Queue() Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default growth factor
Queue(ICollection) Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial
capacity as the number of elements copied, and uses the default growth factor
Queue(Int32) Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor
Queue(Int32, Single) Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor
Trang 30Một số cấu trúc dữ liệu Queue – Methods
Contains Determines whether an element is in the Queue
CopyTo Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index
Dequeue Removes and returns the object at the beginning of the Queue
Enqueue Adds an object to the end of the Queue
Peek Returns the object at the beginning of the Queue without removing it
TrimToSize Sets the capacity to the actual number of elements in the Queue
Trang 32 Hiện thực giao diện IList, sử dụng 1 mảng có kích thước có thể thay đổi nếu cần.
Thuộc namespace: System.Collections.
Capacity của ArrayList là số lượng các phần tử mà ArrayList có thể chứa, khi 1 phần tử được thêm vào, Capacity có thể tăng nếu cần Giá trị Capacity có thể giảm khi sử dụng phương thức TrimToSize() hoặc gán giá trị Thuộc tính Count là số phần tử hiện có trong ArrayList.
Sử dụng index để truy cập các phần tử của ArrayList, index cơ sở là 0.
Các phần tử có thể có kiểu dữ liệu khác nhau, cho phép giá trị null
Trang 33Các cấu trúc tập hợp ArrayList - Example
public class SamplesArrayList {
public static void Main() {
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList ();
myAL.Add( "Hello" );
myAL.Add( "World" );
myAL.Add( "!" );
// Displays the properties and values of the ArrayList.
Console WriteLine( "myAL" );
Console WriteLine( " Count: {0} " , myAL.Count );
Console Write( " {0} " , obj );
Console WriteLine();
} }
Trang 34Các cấu trúc tập hợp ArrayList – Constructor
ArrayList() Initializes a new instance of the ArrayList class that is empty and has the default initial capacity
ArrayList(ICollection) Initializes a new instance of the ArrayList class that contains elements copied from the specified collection
and that has the same initial capacity as the number of elements copied
ArrayList(Int32) Initializes a new instance of the ArrayList class that is empty and has the specified initial capacity
Trang 35Các cấu trúc tập hợp ArrayList – Methods
Add Adds an object to the end of the ArrayList
AddRange Adds the elements of an ICollection to the end of the ArrayList
BinarySearch Overloaded Uses a binary search algorithm to locate a specific element in the sorted ArrayList or a portion of it
Clear Removes all elements from the ArrayList
Clone Creates a shallow copy of the ArrayList
Contains Determines whether an element is in the ArrayList
CopyTo Overloaded Copies the ArrayList or a portion of it to a one-dimensional array
IndexOf Overloaded Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it
Trang 36Các cấu trúc tập hợp ArrayList – Methods
Insert Inserts an element into the ArrayList at the specified index.
InsertRange Inserts the elements of a collection into the ArrayList at the specified index.
LastIndexOf Overloaded Returns the zero-based index of the last occurrence of a value in the ArrayList or in a portion of it.
Remove Removes the first occurrence of a specific object from the ArrayList.
RemoveAt Removes the element at the specified index of the ArrayList.
RemoveRange Removes a range of elements from the ArrayList.
Sort Overloaded Sorts the elements in the ArrayList or a portion of it.
ToArray Overloaded Copies the elements of the ArrayList to a new array.
TrimToSize Sets the capacity to the actual number of elements in the ArrayList.
Trang 37Biểu diễn danh sách các đối tượng, có thể truy cập bằng index.
Cung cấp các phương thức: tìm kiếm, sắp xếp và các thao tác với danh sách.
37
Trang 38Các cấu trúc tập hợp List – Constructor
- Khởi tạo danh sách chứa các phần tử được sao chep từ một tập hợp (mảng)
- Capacity được khởi tạo băng sô phần tử được sao chep.
List<T>(Int32) - Khởi tạo danh sách trông.
- Capacity băng giá trị tham sô truyền vào.
Trang 39Các cấu trúc tập hợp List – Properties
Capacity Get hoặc set tổng sô phần tử trong câu truc dữ liệu List có thể lưu trữ mà không cần phải thay đổi kích thước.
Count Get sô lượng phần tử trong List<T>.
Item Truy cập phần tử bât kỳ sử dụng Indexer của List
Trang 40Các cấu trúc tập hợp List – Methods
AddRange Thêm tập các phần tử từ một tập hợp (mảng) vào cuôi List<T>
BinarySearch(T) Tìm kiếm một phần tử trong toàn bộ danh sách sắp xếp, sử dụng phep so sánh mặc định, trả về index của phần tử được
tìm thây (-count: không tìm thây)
BinarySearch(T, IComparer<T>) Tìm kiếm 1 phần tử trong toàn bộ danh sách sắp xếp sử dụng phep so sánh cụ thể Trả về index của phần tử được tìm
thây
BinarySearch(Int32, Int32, T, IComparer<T>) Tìm kiếm trong một phạm vi của danh sách sắp xếp sử dụng phep so sánh cụ thể Trả về index của phần tử được tìm
thây
Trang 41Các cấu trúc tập hợp List – Methods
Clear Xóa toàn bộ các phần tử trong danh sách
Contains Xác định xem phần tử có trong danh sách hay không
CopyTo(T[]) Sao chep toàn bộ danh sách sang mảng 1 chiều Bắt đầu từ chi sô đầu trong mảng đích.
CopyTo(T[], Int32 arri) Sao chep toàn bộ danh sách sang mảng 1 chiều Bắt đầu từ chi sô arri trong mảng đích.
CopyTo(Int32 id, T[], Int32 arri, Int32 count) Sao chep một sô phần tử từ danh sách ra mảng một chiều Bắt đầu từ vị trí arri trong mảng đích.
Exists Xác định danh sách có chứa các phần tử thỏa mãn điều kiện cho trước.
Finalize Cho phep đôi tượng giải phóng tài nguyên, thưc hiện các thao tác dọn dep trước khi bộ thu dọn rác (garbage
collection) làm việc với nó.
Trang 42Các cấu trúc tập hợp List – Methods
Find Tìm kiếm 1 phần tử thỏa mãn điều kiện cho trước, trả về phần tử thỏa mãn đầu tiên
FindAll Trả về tât cả các phần tử thỏa mãn điều kiện cho trước
FindIndex(Predicate<T>) Tìm kiếm 1 phần tử thỏa mãn điều kiện cho trước, trả về index phần tử thỏa mãn đầu tiên
FindIndex(Int32 id, Predicate<T>) Tìm kiếm 1 phần tử trong phạm vi từ vị trí id đến cuôi danh sách, thỏa mãn điều kiện cho trước, trả về index phần tử thỏa
mãn đầu tiên
FindIndex(Int32 startid, Int32 count,
Predicate<T>)
Tìm kiếm 1 phần tử thỏa mãn điều kiện đã định nghĩa, trả về index của phần tử xuât hiện dầu tiên
Phạm vi tìm kiếm từ startid, sô lượng phần tử trong phạm vi tìm kiếm là count