模板函数实现vector元素去重
template <typename T>//先声明模板参数 T void RemoveSameElement1(vector<T>& v) { std::unordered_set<T> existed; for (auto iter = v.begin(); iter != v.end();) { if (existed.find(*iter) != existed.end()) { iter = v.erase(iter); } else { existed.insert(*iter); ++iter; } } } template <typename T>//先声明模板参数 T void RemoveSameElement2(vector<T>& v) { std::unordered_set<T> existed; vector<T> vTmp; vTmp.reserve(v.size()); for (auto iter = v.begin(); iter != v.end(); ++iter) { if (existed.find(*iter) == existed.end()) { existed.insert(*iter); vTmp.push_back(*iter); } } vTmp.swap(v); }
调用示例:
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; RemoveSameElement1(v);
cout << "去重:" << endl; sort(v.begin(), v.end()); for (size_t i = 0 ; i < v.size(); ++i) { cout << v[i] << " "; } cout << endl; return 0; }