C + + vector traversal Delete element error problem

Source: Internet
Author: User
When using iterator traversal, delete one of the problems, the result is that the deletion of one can not be used since the increase

C + + vector traversal Delete element
has been not familiar with the vector deletion operation, is now sorted out. The first three sections add some knowledge, and then part fourth gives the sample code.
I. Earse method of Vector
Iterator Erase (iterator position);
Iterator Erase (iterator, iterator last);

Erase ElementsRemoves from the vector container either a single element (position) or a range of elements ([First,last)).

This effectively reduces is the vector size by the number of elements removed and calling each element ' s destructor before.

Because vectors keep a array format, erasing on positions other than the vector end alsomovesAll of the elements after the segment erased to their new positions, which could not is a method as efficient as erasing in oth Er kinds of sequence containers (deque, list).

This is invalidates all iterator and references to elements after position or.

ParametersAll parameters are of the member type iterator, which in vector containers are as a defined access random type.
Position iterator pointing to a single element to is removed from the vector. The iterators specifying a range within the vector to is removed: [first,last). i.e., the range includes all the elements between-I, including the element pointed by-I E pointed by last.

return valueA random access iterator pointing toThe new location of the element that followed the last element erasedBy the function call, the which are the vector end if the operation erased the last element in the sequence.

======================================= I am the industrious dividing line =========================================

Ii. about Remove_if (<algorithm>)

ForwardIterator remove_if (ForwardIterator, ForwardIterator last,
predicate pred);

Remove elements from range Removes from the range [First,last] the elements for which pred applied to it value is true and returns a It Erator to the "new" range, which now includes only the values for which pred is false.

The behavior of this function template are equivalent to:

1
2
3
4
5
6
7
8
9
Template < class ForwardIterator, class predicate >
  forwarditerator remove_if (ForwardIterator-A, Forwardi Terator,
                              predicate pred)
{forwarditerator result = i
  ;
  for (; I!= last; ++first)
    if (!pred (*first)) *result++ = *first;
  return result;
}
Notice that this function does not alter the elements past the "new End", which keep their old values and are still Le.

return value

A forward iterator pointing to the "new end of the" sequence, which now includes "all" for elements which is false.

======================================= I am the industrious dividing line =========================================

Iii. about the Find () function
function Template <algorithm>

Template <class Inputiterator, class t> Inputiterator find (Inputiterator-I, Inputiterator last
   , const T&AM P Value);

Find value in range Returns an iterator to the "the" in the range [first,last) that compares equal to value, or last if not F Ound.

The behavior of this function template are equivalent to:

1
2
3
4
5
6
Template<class Inputiterator, class t>
  inputiterator find (Inputiterator-I, Inputiterator last, const T&AM P Value)
  {for
    (; first!=last; first++) if (*first==value) break;
    Return to the
  

Return Vaule:an iterator to the ' the ' the ' the ' range that matches value.
If no element matches, the function returns last.

======================================= I am the industrious dividing line =========================================

Four, the following code to demonstrate the vector of the deletion element method, which uses three macro DEMO1, DEMO2, DEMO3 The purpose is to enable a file to demonstrate a few examples. When demonstrating a different demo, just add the-D macro name at compile time. To demonstrate DEMO2, compile as follows:

g++ Vectordelete.cpp-o vec-d DEMO2

C + + Language: C + + vector delete operation

001/*
002 date:2010.6.25
003 Content: Traversal deletion of vectors
004 any operation that alters the vector length will invalidate the existing iterator. For example, after invoking Push_back, you can no longer trust the value of an iterator that points to a vector.
51 principles: As long as the vector to delete or increase the action, it is necessary to show that the iterator has been invalid, must be retrieved from the vector object to the new iterator value, rather than the temporary variable, the suffix of the method
006 */
007 #include <iostream>
008 #include <vector>
009 #include <string>
010 #include <cstring>
011 #include <list>
012 #include <algorithm>//to Use remove_if
013using namespaceStd
014
015
016typedefvector<int> V;
017typedefvector<int>::iterator VIT;
018typedeflist<int> L;
019typedeflist<int>::iterator LIT;
020 v V;
021 L Lis;
022
023
024class InList
025 {
026 Public:
027 InList (list<int> &lis): Li (Lis) {}
028
029bool operator()(intN
030 {
031 returnFind (Li.begin (), Li.end (), N)!=li.end ();
032}
033Private:
034 list<int> &li;
035};
036
037
13YintMain ()
039 {
040 for(intI=0; i<Ten; ++I)//initialization v:0 1 2 3 4 5 6 7 8 9
041 v.push_back (i);
042 for(intI=0; i<5; ++I)//initialization lis:0 1 2 3 4
043 Lis.push_back (i);
24v
045 VIT it;
046//cout<<endl<<v.end ()-v.begin () <<endl; The iterator of the vector container supports the addition and subtraction operation, which is rarely seen in other types of iterators
047
048 #ifdef DEMO1
049//Traversal the correct way to remove elements that are not equal to 3 in V
050 for(It=v.begin (); It!=v.end ();)
051 {
052if(*it!=3)
053 {
054//Assign it to the return value of erase (), which points to the new location of the element that followed to the last element erased
055 it = v.erase (it);
056}
15VElse
058 ++it;
059}
060 for(It=v.begin (); It!=v.end (); ++it)
061 cout<<*it<<endl;
062 #endif
063
064 #ifdef DEMO2
065//demo2 function: In V, delete those elements that exist both in V and in the LIS, without using the remove_if
066 it = V.begin ();
067 VIT del = it;
068 for(; It!=v.end (); ++it)
069 {
070if(Find (Lis.begin (), Lis.end (), *it) = = Lis.end ())
071 {
072 *del++ = *it;
073}
074}//At this point, Del points a iterator pointing to the "new end of the" Sequence,which now includes all the elements which are not In Lis.
075//The entire V becomes 5 6 7 8 9 5 6 7 8 9, where the Del points to the second 5
076 v.erase (del, V.end ());
077 for(It=v.begin (); It!=v.end (); ++it)
078 cout<<*it<<endl;
079 #endif
080
081 #ifdef DEMO3
082

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.