I've made a little function to eliminate continuous duplicate from a std::vector. I have to use C++03.
For example, if a vector of ints is composed of: 1,1,2,3,,3,1,1,2 my function should return 1,2,3,1,2. I've tried to use templates (I've just began to use c++) and made it as fast as possible!
template<class T>
vector<T> remove_duplicate(vector<T>& vec) {
int length = vec.size();
vector<T> result(length);
result[0] = vec[0];
int last = 0;
for(int i=0; i<length; i++)
if(vec[i] != result[last]){
last++;
result[last] = vec[i];
}
result.resize(last+1);
return result;
}
Here's a simple test case:
static
void test_remove_duplicate() {
vector<int> v;
v.push_back(1); //123131
v.push_back(1);
v.push_back(2);
v.push_back(2);
v.push_back(3);
v.push_back(1);
v.push_back(3);
v.push_back(3);
v.push_back(1);
v.push_back(1);
vector<int> v1;
v1 = remove_duplicate(v);
for(int i=0; i<v1.size(); i++) {
cout << v1[i];
} cout << endl;
}
What do you think about it?