+ Reply to Thread
Results 1 to 2 of 2

Thread: Why map stores a key and value even if I search for key?

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    23

    Why map stores a key and value even if I search for key?

    I have following code:

    Code:
    void UseMap()
    {
    	std::map<int, int> keyValueMap ;
    
    	keyValueMap[10] = 10 ;
    	keyValueMap[20] = 20 ;
    	keyValueMap[30] = 30 ;
    
    	int nValue = keyValueMap[10] ;
    
    	OutputDebugString("Before searching for 40\n") ;
    	std::map<int, int>::iterator itr = keyValueMap.begin() ;
    	for (; itr != keyValueMap.end(); itr++)
    	{
    		char szMessage[1024] ;
    		sprintf(szMessage, "Key : %d, Value : %d\n", itr->first, itr->second) ;
    		OutputDebugString(szMessage) ;
    	}
    
    	//why this statement store the new key 40 with value 0 in the map?
    	nValue = keyValueMap[40] ;
    
    	OutputDebugString("After searching for 40\n") ;
    	itr = keyValueMap.begin() ;
    	for (; itr != keyValueMap.end(); itr++)
    	{
    		char szMessage[1024] ;
    		sprintf(szMessage, "Key : %d, Value : %d\n", itr->first, itr->second) ;
    		OutputDebugString(szMessage) ;
    	}
    }
    I have search using [] operator of map.

    It has inserted new element with the search parameter and value is initialized with 0.

    Am I doing anything wrong?

    Please help.

  2. #2
    To find/search an element in the map use map:find member.

    The technique you used inserts an element in the ma if it does not exists!

    Solution can be:

    Code:
    void UseMap()
    {
    	std::map<int, int> keyValueMap ;
    
    	keyValueMap[10] = 10 ;
    	keyValueMap[20] = 20 ;
    	keyValueMap[30] = 30 ;
    
    	int nValue = keyValueMap[10] ;
    
    	OutputDebugString("Before searching for 40\n") ;
    	std::map<int, int>::iterator itr = keyValueMap.begin() ;
    	for (; itr != keyValueMap.end(); itr++)
    	{
    		char szMessage[1024] ;
    		sprintf(szMessage, "Key : %d, Value : %d\n", itr->first, itr->second) ;
    		OutputDebugString(szMessage) ;
    	}
    
    	
    	itr = keyValueMap.find(40) ;
    
    	if (itr != keyValueMap.end())
    	{
    		nValue = itr->second ;
    	}
    
    	OutputDebugString("After searching for 40\n") ;
    	itr = keyValueMap.begin() ;
    	for (; itr != keyValueMap.end(); itr++)
    	{
    		char szMessage[1024] ;
    		sprintf(szMessage, "Key : %d, Value : %d\n", itr->first, itr->second) ;
    		OutputDebugString(szMessage) ;
    	}
    }

+ 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