add Vector class(unfinished

This commit is contained in:
Shine wOng
2019-05-08 11:00:10 +08:00
parent fae4437d18
commit 75ae7e0800
3 changed files with 127 additions and 0 deletions

55
thu_dsa/chp2/Vector.cpp Normal file
View File

@@ -0,0 +1,55 @@
#include "Vector.h"
//protected methods
template <typename T>
void Vector::copyfrom(T* const A, int lo, int hi){
int ix = 0;
while (lo != hi) _elem[ix++] = A[lo++];
}
template <typename T>
void Vector::copyfrom(Vector<T>& const V, int lo, int hi){
copyfrom(V._elem, lo, hi);
}
//constructors
template<typename T>
Vector::Vector() {
_capacity = DEFAULT_CAPACITY;
_size = 0;
_elem = new T[_capacity];
}
template<typename T>
Vector::Vector(int capacity) {
_capacity = capacity;
_size = 0;
_elem = new T[_capacity];
}
template<typename T>
Vector::Vector(T* const A, int lo, int hi){
_capacity = MAX(DEFAULT_CAPACITY, (hi - lo) >> 1);
_size = hi - lo;
copyfrom(A, lo, hi);
}
template<typename T>
Vector(Vectort<T>& const V){
_size = V.getSize();
_capacity = _size >> 1;
copyfrom(V._elem, 0, _size);
}
template<typename T>
Vector::Vector(Vector<T>& const V, int lo, int hi){
_capacity = MAX(DEFAULT_CAPACITY, (hi - lo) >> 1);
_size = hi - lo;
copyfrom(V, lo, hi);
}
//read-only interfaces
template<typename T>
Vector::print(){
}

57
thu_dsa/chp2/Vector.h Normal file
View File

@@ -0,0 +1,57 @@
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
#define DEFAULT_CAPACITY 3
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
using std::cout;
using std::endl;
template<typename T>
class Vector{
protected:
T* _elem;
int _size;
int _capacity;
//protected methods
void copyfrom(T* const A, int lo, int hi);
void copyfrom(Vector<T>& const V, int lo, int hi);
void expand();
void shrink();
public:
//constructors
Vector();
Vector(int capacity);
Vector(T* const A, int n);
Vector(T* const A, int lo, int hi);
Vector(Vectort<T>& const V);
Vector(Vector<T>& const V, int lo, int hi);
//deconstructor
~Vector();
//read-only interfaces
void print(void);
int find(T& const elem);
int find(T& const elem, int lo, int hi);
int getSize() { return _size; }
int getCapacity(){return _capacity}
//writable interfaces
T& get(int index);
T& put(int index, T& elem);
T& operator[](int index) const;
int push_back(T& const elem);
int insert(T& const elem);
T pop_back(void);
T pop(int index);
T pop(int hi, int lo);//return the last element popped
int remove(T& const elem);
};
#endif

View File

@@ -0,0 +1,15 @@
#include <cassert>
#include <time.h>
#include "Vector.h"
void test_constructor(){
cout << "--------------run test_constructo--------------" << endl;
Vector<int> V();
assert(V.getSize() == 0);
assert(V.getCapacity() == DEFAULT_CAPACITY);
int A[10] = { 2,3,4,6,1,0,9,8,7,5 };
Vector<int> V(A, 10);
}