+ Reply to Thread
Results 1 to 2 of 2

Thread: How to delete an item from vector in a loop?

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    37

    How to delete an item from vector in a loop?

    I have following code but it does not doing its work.

    Code:
    void DeleteItem()
    {
    	std::vector<int> myArray ;
    
    	myArray.push_back(1) ;
    	myArray.push_back(2) ;
    	myArray.push_back(3) ;
    	myArray.push_back(4) ;
    	myArray.push_back(5) ;
    
    	std::vector<int>::iterator itr = myArray.begin() ;
    	for(; itr != myArray.end(); itr++)
    	{
    		if (*itr == 2)
    		{
    			myArray.erase(itr) ;
    		}
    		else if (*itr == 3)
    		{
    			myArray.erase(itr) ;
    		}
    	}
    
    	char message[100] ;
    	itr = myArray.begin() ;
    	for(; itr != myArray.end(); itr++)
    	{
    		sprintf(message, "data %d.\n", *itr) ;
    		OutputDebugString(message) ;
    	}
    }
    Please help.

  2. #2
    Junior Member
    Join Date
    May 2012
    Posts
    29
    This is little tricky.

    When you erase an item from the vector, it invalidates its iterator.

    So you will need to update iterator after deleting an item.

    Example:

    Code:
    void DeleteItem()
    {
    	std::vector<int> myArray ;
    
    	myArray.push_back(1) ;
    	myArray.push_back(2) ;
    	myArray.push_back(3) ;
    	myArray.push_back(4) ;
    	myArray.push_back(5) ;
    
    	std::vector<int>::iterator itr = myArray.begin() ;
    	for(; itr != myArray.end();)
    	{
    		if (*itr == 2)
    		{
    			itr = myArray.erase(itr) ;
    		}
    		else if (*itr == 3)
    		{
    			itr = myArray.erase(itr) ;
    		}
    		else
    		{
    			itr++ ;
    		}
    	}
    
    	char message[100] ;
    	itr = myArray.begin() ;
    	for(; itr != myArray.end(); itr++)
    	{
    		sprintf(message, "data %d.\n", *itr) ;
    		OutputDebugString(message) ;
    	}
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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