这个问题原本是 C++ 吧里有人问的, 我当时就立刻动手解决了, 结果后来才发现, STL 里已经有了对应的泛型算法了......
看来我对 STL 知道的还是太少, 贴一下我当时完成的方法:
set<int> VecToSet (const vector<int> &vec) { set<int> tmp_set (vec.cbegin (), vec.cend ()); return move (tmp_set); } void EraseSameNum (set<int> &short_set , set<int> &long_set) { for (auto it = short_set.begin (); it != short_set.end ();) { auto loc = long_set.find (*it); if (loc != long_set.end ()) { auto loc2 = it; ++it; short_set.erase (loc2); long_set.erase (loc); } ++it; } } set<int> GetDiffNums (const vector<int> &lhs_vec , const vector<int> &rhs_vec) { set<int> lhs_set = VecToSet(lhs_vec); set<int> rhs_set = VecToSet(rhs_vec); if (lhs_set.size () > rhs_set.size ()) { EraseSameNum (rhs_set, lhs_set); } EraseSameNum (rhs_set, lhs_set); set<int> diff_set (lhs_set); diff_set.insert (rhs_set.begin(), rhs_set.end()); return move (diff_set); } int main() { using int_v = vector<int>; int_v v1{1, 2, 4, 6}; int_v v2{2, 5, 6, 8, 4}; set<int> iset = GetDiffNums(v1, v2); }
刚码好的时候自我感觉还是不错的,直到看到了可以用 STl 的泛型算法解决:
int main () { using int_v = vector<int>; int_v vec1{1, 3, 6}; int_v vec2{2, 3, 8, 3, 7, 6}; sort (vec1.begin(), vec1.end()); sort (vec2.begin(), vec2.end()); set<int> iset; set_symmetric_difference (vec1.begin() , vec1.end() , vec2.begin() , vec2.end() , inserter( iset, iset.begin())); return 0; }
时间: 2024-12-28 12:44:49