There are still many implementation methods for deleting C ++ container values. What we will introduce today is one of the commonly used and simple implementation methods, hoping to help you.
In the process of program development, containers in the C ++ programming language have many values, some of which are useful and some are useless. So how should we delete these useless values? Here we will introduce in detail how to delete the C ++ container value.
Generally, the erase function is provided in the C ++ container. One of the parameters received by this function is generally an iterator:
If you delete the C ++ container value, we may have used it in general:
- List <int> C;
- // Todo insert items
- For (list <int >:: iterator I = C. Begin (); I! = C. End (); ++ I)
- {
- If (* I)> 10)
- {
- // If there is a value greater than 10, delete it
- C. Erase (I );
- Break;
- }
- }
The above code is correct when deleting an element... However, we want to delete all values greater than 10, so:
- List <int> C;
- // Todo insert items
- For (list <int >:: iterator I = C. Begin (); I! = C. End (); ++ I)
- {
- If (* I)> 10)
- {
- // Delete all values greater than 10
- C. Erase (I );
- }
- }
Compilation and running with hope... So an exception occurs... Ah... Oh...
It turns out that after the iterator I is deleted, the element I refers to has expired, and then I ++ is given. It no longer exists...The code for deleting the C ++ container value is as follows:
- List <int> C;
- // Todo insert items
- List <int>: iterator nextitr = C. Begin ();
- For (list <int >:: iterator I = C. Begin ();;)
- {
- If (nextitr = C. End ())
- Break;
- ++ Nextitr;
- If (* I)> 10)
- {
- // If there is a value greater than 10, delete it
- C. Erase (I );
- }
- I = nextitr;
- }
The above code is easy to understand, that is, before deleting an iterator, store its later iterator first, and then use the previously stored iterator in the next loop.
OK, we can see that the above Code can work, and the behavior seems to be correct,... The Code seems to be a little more. I think it is better to reduce the number of codes, and the logic should not be so troublesome. Then let's look at the following code (Reprinted from objective STL ).
- List <int> C;
- // Todo insert items
- For (list <int >:: iterator I = C. Begin (); I! = C. End ();)
- {
- If (* I)> 10)
- {
- // If there is a value greater than 10, delete it
- C. Erase (I ++ );
- }
- Else
- I ++;
- }
Well... A master is a master (I have never cared about the big difference between ++ I and I ++ in the past). I will provide another version, use the remove_if function of list.
- bool fun(int i)
- {
- if(i>10)
- return true;
- else
- return false;
- }
- list<int> c;
- // todo insert items
- c.remove_if(fun);
Well, there are many ways to delete C ++ container values.