+ Reply to Thread
Results 1 to 3 of 3

Thread: Using std::map in C++

  1. #1

    Using std::map in C++

    Hi All,

    Ca I have sample example of Using std::map in C++?

    Regards.

  2. #2
    Please provide simple example.
    Last edited by Yuva; 02-22-2012 at 07:37 AM.

  3. #3
    Hi,

    Please find the sample code:

    Code:
    #pragma once
    
    #include <map>
    #include <string>
    #include <iterator>
    
    bool DeletedThisRoleID(int nRoleID, int nReferenceRoleID)
    {
    	if (nReferenceRoleID == nRoleID)
    	{
    		return true ;
    	}
    
    	return false ;
    }
    
    void UsingMap()
    {
    	//map has two items, a key and its value.
    	typedef std::map<int, std::string> INT_TO_STRING_MAP_TYPE ;
    
    	INT_TO_STRING_MAP_TYPE mapStudent ;
    
    	//it checks if there is an object already preset if not inserts it or replaces it.
    	//this statement is not good if you do not want to replace the existing item!
    	mapStudent[1] = "Rosy" ;
    	mapStudent[2] = "Rudolf" ;
    	mapStudent[3] = "Steven" ;
    
    	//replace the existing item if present...
    	if (mapStudent.find(1) != mapStudent.end())
    	{
    		mapStudent[1] = "Helen" ;
    	}
    
    	//iterate the items...
    	char szName[100] ;
    	INT_TO_STRING_MAP_TYPE::const_iterator itr = mapStudent.begin() ;
    
    	for(; itr != mapStudent.end() ; itr++)
    	{
    		//as we know map has two items,
    		//key is stored in "first" member and 
    		//value is stored in "second" member.
    		sprintf(szName, "RoleId = %d, Name = %s", itr->first, itr->second.c_str()) ;
    	}
    
    	//erase a particular item from the map
    	//please note that we need to have an iterator which can delete the map item...
    	//which should be non constant iterator.
    	INT_TO_STRING_MAP_TYPE::iterator itrDelete = mapStudent.begin() ;
    	for (itrDelete = mapStudent.begin() ; itrDelete != mapStudent.end() ;)
    	{
    		if(DeletedThisRoleID(itrDelete->first, 2))
    		{
    			mapStudent.erase(itrDelete++) ;
    		}
    		else
    		{
    			++itrDelete ;
    		}
    	}
    
    	//again, iterate the items...
    	itr = mapStudent.begin() ;
    	for(; itr != mapStudent.end() ; itr++)
    	{
    		sprintf(szName, "RoleId = %d, Name = %s", itr->first, itr->second.c_str()) ;
    	}
    
    	//erase all the items from map
    	mapStudent.clear() ;
    }
    Regards.

+ 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