简体   繁体   中英

Removing multiple elements from stl list while iterating

This is not similar to Can you remove elements from a std::list while iterating through it? . Mine is a different scenario.

Lets say I have a list like this.

1  2  3  1  2  2  1  3

I want to iterate this stl list in such a way that When I first encounter an element XI do some activity and then I need to remove all the elements X in that list and continue iterating. Whats an efficient way of doing this in c++.

I am worried that when i do a remove or an erase I will be invalidating the iterators. If it was only one element then I could potentially increment the iterator and then erase. But in my scenario I would need to delete/erase all the occurances.

Was thinking something like this

while (!list.empty()) {
   int num = list.front();
   // Do some activity and if successfull
   list.remove(num);
   }

Dont know if this is the best.

Save a set of seen numbers and if you encounter a number in the set ignore it. You can do as 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 will process each value only once and the new_list will only contain the first copy of each element in the old_list . This runs in O(n*log(n)) because each iteration performs a set lookup (you can make this O(n) by using a hashset). This is significantly better than the O(n^2) that your approach runs in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM