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. So let's look at the code below and repost it 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 difference between ++ I and I ++.) Well, 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.