add unique and map method
This commit is contained in:
@@ -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 <typename VST> void map(VST& visit);
|
||||
};
|
||||
|
||||
//protected methods
|
||||
@@ -165,4 +168,27 @@ int Vector<T>::remove(T const &elem){
|
||||
return pos;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
int Vector<T>::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 <typename T>
|
||||
void Vector<T>::map(void(*visit)(T&)){
|
||||
for (int ix = 0; ix != _size; ++ix) visit(_elem[ix]);
|
||||
}
|
||||
|
||||
template <typename T> template <typename VST>
|
||||
void Vector<T>::map(VST& visit) {
|
||||
for (int ix = 0; ix != _size; ++ix) visit(_elem[ix]);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -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<int> v(A, 0, 10);
|
||||
assert(v.unique() == 0);
|
||||
assert(v.getSize() == 10);
|
||||
|
||||
v = Vector<int>(A, 18);
|
||||
assert(v.unique() == 8);
|
||||
assert(v.getSize() == 10);
|
||||
assert(v[9] == 5);
|
||||
|
||||
cout << "test passed." << endl;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
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<float> v(A, 10);
|
||||
|
||||
v.map(Increase);
|
||||
for (int ix = 0; ix != v.getSize(); ++ix)
|
||||
assert(v[ix] == A[ix] + 1);
|
||||
|
||||
cout << "test passed." << endl;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user