Tài liệu LẬP TRÌNH C nâng cao -BÀI 5 - TEMPLATE (TIẾP) part 1 - Pdf 87

LẬP TRÌNH C/C++ NÂNG CAO
Yêu cầu trước khi đọc: học xong Lập trình C/C++ căn bản

BÀI 5: TEMPLATE (TIẾP) part 1
Lại đau đầu
Ta muốn viết một chương trình tìm kiếm phần tử trong một mảng. Ta viết
như sau
CODE
template<class T>int search(T a[],int n,T key)
{
int index=0;
while(index<n && a[index] != key) index++;
if(index == n) return -1;else return index;
}
Sau đó trong hàm main ta viết
CODE
char *list[]={"zero","one","two"}; //thực ra là mảng 2 chiều thôi
search(list,3,"two"); //ồ không, lại so sánh memory address nữa rồi
Nhưng lần này vấn đề phức tạp hơn nhiều. Ví dụ nếu là mảng các Person là
đụng thêm vấn đề cấp phát bộ nhớ nữa
Giải quyết
Chương trình dưới đây trình bày cách tạo một lớp mảng template, với đủ các
chức năng tạo, thêm, truy xuất dữ liệu, toán tử [].
Đặc biệt là giải quyết đau đầu tìm kiếm dữ liệu ở trên vì so sánh memory
address. Lưu ý là khi tạo ta phải dùng reference refers to
pointer để cấp phát bộ nhớ đó
CODE
#include <iostream>
using namespace std;
template<class T>class Array
{

arr = new T[n];
}
template<typename T>T& Array<T>::operator[](int i)
{
return *(array+i);
}
template<typename T>int Array<T>::seek(const T& key)
{
int index=0;
while((index<size) && *(array+index)!=key) ++index;
if(index==size) return -1;
else return index;
}
template<typename T>int Array<T>::search(const T* list,int size,const T key)
{
int index=0;
while((index<size) && *(list+index)!=key) ++index;
if(index==size) return -1;
else return index;
}
class Person
{
int age;
public:
Person(){age=0;}
Person(int age){this->age=age;}
int getAge() const{return age;}
friend bool operator!=(const Person& p1,const Person& p2)
{
return p1.getAge()!=p2.getAge();

“Advance C++” nhưng thực ra trong lập trình game vẫn chỉ
là “newbie”)
prototype template function
Chuẩn bị một tập tin tên là “array.h”
CODE
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
using namespace std;
template<class T>class Array;
template<typename T>bool equal(const Array<T>&,const Array<T>&);
template<typename T>ostream& operator<<(ostream&,const Array<T>&);
template<class T>class Array
{
T* array;int size;
public:
Array(int n);
~Array();
void setValue(const T&,int n);
friend bool equal <>(const Array<T>&,const Array<T>&);
friend ostream& operator<< <>(ostream&,const Array<T>&);
};
#include "array.cpp"
#endif
Chuẩn bị một tập tin tên là “array.cpp”
CODE
template<typename T>Array<T>::Array(int n)
{
size=n;
array = new T[size];


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status