Friday, 15 July 2011

c++ - Iterating through STL containers and removing/adding multiple items -


One of the most frequent errors in my code is that STL containers are modified during a loop .

Elements are removed or added during the loop execution, so I usually go beyond the limit exceptions.

My loop usually looks like this:

 for  (auto and item: items) {// when the item container is modified. .. ... loop logic)   

When multiple items can be deleted, I use this monstrousness:

 for  Index = items. Size () - 1; index & lt; = 0; index -) {if (index> lists; items.size ()) {// multiple items can go to a single loop // Loop argument}}   

It looks bad and this is the other option for me Defense feels bad to use. Due to which many items can be removed due to the events, where one event can remove the elements in any number.

This is some pseudo code, when this happens, then it is clear:

  // for every button in the vector & lt; Button & gt; {// process button events // event vector & lieutenant; Button & gt; // * error * vector & lt; Button & gt; In the second example, imagine a vector containing the following items:  
  // 0 1 2 3 4 5 6 7 8 9 We start our loop on  0  and move elements by element. On  4 , I want to remove the element  1 ,  4  and  9  so we do not use the normal loop   

Use std :: remove_if with a predicate decision Takes to remove the button:

  Boolean requirements are removed (cut buttons and buttons); Vec.erase (std :: removal_if (vec.begin (), vec.end (), and requirements have been removed), vec.end ());  Edit : For your previous example, there is a quadratic (poor performance) algorithm:  
  std :: vector & lt; Integer & gt; Vec = {0,1,2,3,4,5,6,7,8,9}; Auto end = vec.end (); (For auto = vec.begin (); this is & lt; end; ++) {std :: set & lt; Int & gt; Bad = {1, 4, 9}; End = std :: remove_if (vec.begin (), end, [bad] (int x) {return (bad.find (x)! = Bad.end ());}); } Vec.erase (end, vec.end ());   

You can probably look better using a container (such as a set, or a map).

No comments:

Post a Comment