CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2007
    Posts
    4

    Removing elements from a LIST or VECTOR untill empty

    Hello,

    i'm having troubles with a piece of code where I have a VECTOR and do some tasks with the elements untill this VECTOR is empty.

    while ( !segments.empty() )
    {

    subsegments.clear(); // clear subsegments
    bool first=true;
    for(ii=segments.begin(); ii!=segments.end(); ii++)
    {
    segment=*ii;
    if (first == true)
    {
    first = false;
    refelev=segment.elev;
    }
    if ((fabs (segment.elev-refelev)) < 0.001)
    {
    subsegments.push_back(segment); /// add element to subsegments
    segments.erase( ii );
    ii--;
    }
    }

    ...

    }

    It seems to go wrong with the i--

    The wierd thing is this works fine in VC2003 but now that i'm using 2005 it doesn't.

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Removing elements from a LIST or VECTOR untill empty

    When erasing from a sequential container in this manner, the basic
    algorithm is to :

    a) do no have an increment section in the for statement
    b) if doing an erase, use the return value to get to the next iterator
    c) else increment the iterator by hand

    Code:
            for(ii=segments.begin(); ii!=segments.end(); /* nothing here */  ) 
            { 
                segment=*ii;
                if (first == true)
                {
                    first = false;
                    refelev=segment.elev;
                }
                if ((fabs (segment.elev-refelev)) < 0.001)
                { 
                    subsegments.push_back(segment); /// add element to subsegments
                    ii =  segments.erase( ii );
                }
                else
                {
                    ++ii
                }
            }

  3. #3
    Join Date
    Dec 2007
    Posts
    4

    Thumbs up Re: Removing elements from a LIST or VECTOR untill empty

    Thank you very much !

    I'm gonna try this !

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