+ Reply to Thread
Results 1 to 2 of 2

Thread: In std::map, should we use [] or map::find to find a key?

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

    In std::map, should we use [] or map::find to find a key?

    In std::map, should we use [] or map::find to find a key?

    Which is best way to find key?

    Thanks.

  2. #2
    Junior Member
    Join Date
    Apr 2012
    Posts
    38
    You should use map::find procedure to find the element in the map.

    if you use [] operator of map then it will add the element in the map if it is not present!

    Example:

    Code:
    void UseMap()
    {
    	std::map<int, std::string> myMap ;
    
    	myMap.insert(std::pair<int, std::string>(1, "Roger")) ;
    	myMap.insert(std::pair<int, std::string>(2, "Kruger")) ;
    	myMap.insert(std::pair<int, std::string>(3, "Kate")) ;
    	myMap.insert(std::pair<int, std::string>(4, "Moss")) ;
    
    	int nSize = myMap.size() ;//size is 4
    	std::string strName = myMap[5] ;
    	nSize = myMap.size() ; //size is 5
    
    	std::map<int, std::string>::iterator itr = myMap.find(5) ;
    
    	if (itr != myMap.end())
    	{
    		//element found.
    	}
    	else
    	{
    		//element does not exist.
    	}
    
    	nSize = myMap.size() ; //size is 5
    }

+ 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