+ Reply to Thread
Results 1 to 2 of 2

Thread: Problem deleting item std::map and std::vector in while/for loop

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    49

    Problem deleting item std::map and std::vector in while/for loop

    Hi All,

    I just started exlporing std::map and std::vector but facing problem deleting item in while/for loop.

    Can anyone please help?

    Thanks.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Following is the code to delete an item from map within for loop:

    Code:
    bool IsThisRoleIDToBeDeleted(int nRoleID)
    {
    	if (2 == nRoleID)
    	{
    		return true ;
    	}
    
    	return false ;
    }
    
    void DeleteItemFromMap()
    {
    	typedef std::map<int, std::string> MAPROLEIDTONAME_TYPEDEF ;
    	
    	MAPROLEIDTONAME_TYPEDEF mapRoleIDToName ;
    
    	mapRoleIDToName[1] = "David" ;
    	mapRoleIDToName[2] = "Rosy" ;
    	mapRoleIDToName[3] = "Mark" ;
    
    	MAPROLEIDTONAME_TYPEDEF::iterator itr ;
    
    
    	for (itr = mapRoleIDToName.begin() ; itr != mapRoleIDToName.end() ;itr++)
    	{
    		printf("Role ID = %d, Name = %s\n", itr->first, itr->second.c_str()) ;
    	}
    
    	for (itr = mapRoleIDToName.begin() ; itr != mapRoleIDToName.end() ;)
    	{
    		if(IsThisRoleIDToBeDeleted(itr->first))
    		{
    			mapRoleIDToName.erase(itr++) ;
    		}
    		else
    		{
    			++itr ;
    		}
    	}
    
    	for (itr = mapRoleIDToName.begin() ; itr != mapRoleIDToName.end() ;++itr)
    	{
    		printf("Role ID = %d, Name = %s\n", itr->first, itr->second.c_str()) ;
    	}
    }

+ Reply to 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