diff --git a/thu_dsa/chp2/Vector.h b/thu_dsa/chp2/Vector.h index 9829fab..2ef7ba0 100644 --- a/thu_dsa/chp2/Vector.h +++ b/thu_dsa/chp2/Vector.h @@ -54,6 +54,9 @@ public: T pop(int index); T pop(int lo, int hi);//return the last element popped int remove(T const &elem);//remove first element matched, return index, -1 if not found + int unique(void); //return the number of elements deleted + void map(void(*visit)(T&)); + template void map(VST& visit); }; //protected methods @@ -165,4 +168,27 @@ int Vector::remove(T const &elem){ return pos; } +template +int Vector::unique(){ + int count = 0; + for(int pos = 1; pos != _size;){ + if (find(_elem[pos], 0, pos) == -1) ++pos; + else{ + pop(pos); + ++count; + } + } + return count; +} + +template +void Vector::map(void(*visit)(T&)){ + for (int ix = 0; ix != _size; ++ix) visit(_elem[ix]); +} + +template template +void Vector::map(VST& visit) { + for (int ix = 0; ix != _size; ++ix) visit(_elem[ix]); +} + #endif diff --git a/thu_dsa/chp2/testVector.cpp b/thu_dsa/chp2/testVector.cpp index 0ccc6ed..a98d5fb 100644 --- a/thu_dsa/chp2/testVector.cpp +++ b/thu_dsa/chp2/testVector.cpp @@ -10,6 +10,8 @@ void test_access(); void test_insert(); void test_delete(); void test_find(); +void test_unique(); +void test_map(); int main(){ test_constructor(); @@ -17,6 +19,8 @@ int main(){ test_insert(); test_delete(); test_find(); + test_unique(); + test_map(); system("pause"); return 0; @@ -120,3 +124,32 @@ void test_find(){ cout << "test passed." << endl; } + +void test_unique(){ + cout << "run test_unique..."; + int A[] = { 2,3,4,6,1,0,9,8,7,5,9,2,3,5,6,3,3,5 }; + Vector v(A, 0, 10); + assert(v.unique() == 0); + assert(v.getSize() == 10); + + v = Vector(A, 18); + assert(v.unique() == 8); + assert(v.getSize() == 10); + assert(v[9] == 5); + + cout << "test passed." << endl; +} + +template +void Increase(T & elem) { ++elem; } +void test_map(){ + cout << "run test_map..."; + float A[] = { 2,3,4,6,1,0,9,8,7,5,9,2,3,5,6,3,3,5 }; + Vector v(A, 10); + + v.map(Increase); + for (int ix = 0; ix != v.getSize(); ++ix) + assert(v[ix] == A[ix] + 1); + + cout << "test passed." << endl; +}