CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2000
    Posts
    204

    why my program can not run correctly?

    why my program can not run correctly?

    m_lstA.remove(*iter); <-----error!!!!


    ///// part code as follow:

    Code:
    class A  
    {
    public:
      A();
      virtual ~A();
      bool operator== (const A& rhs){
    	return rhs.m_strName == m_strName && rhs.m_nNum == m_m_nNum;
      };
    
      CString m_strName;			//
      int m_nNum;
    };
    
    ....
    	
    std::list<A> m_lstA;
    
    ......
    
    std::list<A>::iterator iter = m_lstA.begin();
    for(; iter != m_lstA.end(); ++iter){
      if(iter->m_strName == strName){
        m_lstA.remove(*iter);   <----error!!!!!!!!
      }
    }
    First know what you don't know, then you will know what you will know

  2. #2
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    Your code doesn't work because remove() will invalidate iter.
    Code:
    std::list<A>::iterator iter = m_lstA.begin(), r_i;
    for(; iter != m_lstA.end(); ){
      if(iter->m_strName == strName){
        r_i = iter++;
        m_lstA.remove(*r_i);  
      }
      else{
          ++iter;
      }
    }
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

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