在实际工作中,经常遇到数组元素去重的需求,往往是根据一定的规则去除符合的元素,我通过函数模板实现了一个简单的容器去重功能,记录下来,分享给大家!需要注意的是模板函数使用到了“==”运算符,因此,对于容器的元素类型,需要实现重载“==”运算符,切记!
template <typename T>//先声明模板参数 T void RemoveSameElement(vector<T>& objs) { vector<int> indexs; for (size_t i = 0; i < objs.size(); ++i) { for (size_t j = i + 1; j < objs.size(); ++j) { if (objs[i] == objs[j]) { indexs.push_back(i);//记录i的索引 break; } } } //从后往前批量删除重复数据 for (vector<int>::reverse_iterator iter = indexs.rbegin(); iter != indexs.rend(); ++iter) { objs.erase(objs.begin() + *iter); } }
调用示例:
int _tmain(int argc, _TCHAR* argv[]) { vector<int> v; v.push_back(8); v.push_back(1); v.push_back(4); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); v.push_back(4); v.push_back(3); v.push_back(1); v.push_back(4); v.push_back(6); v.push_back(8); cout << "输入:" << endl; for (size_t i = 0 ; i < v.size(); ++i) { cout << v[i] << " "; } cout << endl << "排序:"<< endl; sort(v.begin(), v.end()); for (size_t i = 0 ; i < v.size(); ++i) { cout << v[i] << " "; } cout << endl; RemoveSameElement(v); cout << "去重:" << endl; sort(v.begin(), v.end()); for (size_t i = 0 ; i < v.size(); ++i) { cout << v[i] << " "; } cout << endl; return 0; }