code template
Hãy thay đổi định nghĩa trên của lớp Vector thành định nghĩa cho một khuôn mẫu Vector (Class template) với tham số là kiểu của phần tử trong Vector
Viết phần cài đặt cho template trên.
Code :
#include <iostream>
using namespace std;
template <class T>
class Vector {
private :
int cap;
int size;
T* p;
public :
Vector ();
Vector (int c);
~Vector();
T getFirst() const;
int getSize() const;
T& operator [] (int pos) const;
void Pop();
void Push(T item);
void Clear();
int IsEmpty() const;
// code here maybe use to boolean
// Example : bool IsEmpty() const;
};
// Detail
template <class T>
Vector<T>::Vector() {
// User define
// Example :size max = 1000
this->cap = 1000;
// initial size = 0
this->size = 0;
this->p = NULL;
}
template <class T>
Vector<T>:: Vector(int c) {
this->size = c;
p = new T[this->size];
// or p = new T[c];
}
template <class T>
Vector<T>:: ~Vector() {
delete [] p;
}
template <class T>
T Vector<T>:: getFirst() const {
return this->p[0];
}
template <class T>
int Vector<T>:: getSize() const {
return this->size;
}
template <class T>
T& Vector<T>:: operator [] (int pos) const {
if (pos >= 0 && pos < this->size) {
return this->p[-- pos];
} else {
cout << "Enter pos not in range [0, this->size - 1]" << endl;
}
}
template <class T>
void Vector<T>::Pop() {
-- this->size;
}
template <class T>
void Vector<T>::Push(T item) {
int i; // counter
++ this->size;
T* contro = new T[this->size];
for (i = 0; i < this->size - 1; i ++) {
contro[i] = this->p[i];
}
contro[this->size - 1] = item;
p = contro;
}
template <class T>
void Vector<T>:: Clear() {
this->size = 0;
this->p = NULL;
}
template <class T>
int Vector<T>:: IsEmpty() const {
// 0 equivalent false
// 1 equivalent true
if (this->size == 0) return 0;
return 1;
}
/*
// or code
template <class T>
bool IsEmpty() const {
if (this->size == 0) return false;
return true;
}
*/
int main ()
{
Vector<int> V;
getchar();
}
Bạn đang đọc truyện trên: Truyen2U.Com