c++ - Removing multiple elements from stl list while iterating -
this not similar can remove elements std::list while iterating through it?. mine different scenario.
lets have list this.
1 2 3 1 2 2 1 3
i want iterate stl list in such way when first encounter element x activity , need remove elements x in list , continue iterating. whats efficient way of doing in c++.
i worried when remove or erase invalidating iterators. if 1 element potentially increment iterator , erase. in scenario need delete/erase occurances.
was thinking this
while (!list.empty()) { int num = list.front(); // activity , if successfull list.remove(num); }
dont know if best.
save set of seen numbers , if encounter number in set ignore it. can follows:
list<int> old_list = {1, 2, 3, 1, 2, 2, 1, 3}; list<int> new_list; set<int> seen_elements; for(int el : old_list) { if (seen_elements.find(el) == seen_elements.end()) { seen_elements.insert(el); new_list.push_back(el); } } return new_list;
this process each value once , new_list
contain first copy of each element in old_list
. runs in o(n*log(n)) because each iteration performs set lookup (you can make o(n) using hashset). better o(n^2) approach runs in.
Comments
Post a Comment