CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 25

Threaded View

  1. #1
    Join Date
    May 2009
    Location
    Boston
    Posts
    375

    remove multiple elements from vector in a loop

    I have a vector,
    Code:
    std::vector<int> myVector;
    
    myVector[0] = 3;
    myVector[1] = 4;
    myVector[2] = 5;
    and I need to remove certain elements, in this case [1] and [2]. This is happening in a loop where some things are evaluated, and under certain circumstances, and element is removed.
    Code:
    for(i=0; i<myVector.size(); i++) {
       if(myVector[i] == 4 || myVector[i] == 5) {
          myVector.erase( myVector.begin()+i );
       }
    }
    the logic is simplified here. The output after this loop is,
    myVector.size() = 2
    myVector[0] = 3;
    myVector[1] = 5;

    As I read this, when myVector[i] == 3, control falls through and nothing happens. When myInt[i] == 4, myVector.begin()+i = 0+1 and myVector[1] is erased. When myVector[i] == 5, myVector.begin()+i = 0+2 and myVector[2] is erased. Element [2] doesn't exist anymore, so the value 5 remains on the list. Obviously I'm not using the iterator properly.

    The iterator position needs to be dynamic to take into account the changing size of the vector, but I can't see how to do that. This seems like a simple issue, so I presume I am missing something here. I can't just loop through and look for 4 or 5, the logic is more complex than that. I need to know how to recursively remove elements from a vector, taking into account the fact that the vector size changes.

    Maybe I need to loop differently. It's almost like I need to repeat the value of i in a case where a given i was removed. This has to work in larger vectors where the elements to be removed can occur in any element. I guess I could just set i=0 after each element is removed and repeat from the top, but that doesn't seem like the best solution either.

    LMHmedchem
    Last edited by LMHmedchem; May 18th, 2011 at 02:10 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured