+ Reply to Thread
Results 1 to 2 of 2

Thread: Using std::multiset in C++

  1. #1

    Using std::multiset in C++

    Hi All,

    Can any one give me example of std::multiset in C++?

    Thanks.

  2. #2
    Hi,

    std::multiset stores Key of specified type in sorted order.
    It is an associative container. It can store multiple keys with same value.

    Example:
    Code:
    #include <set>
    #include <string>
    #include <algorithm>
    #include <iterator>
    
    void UseMultiset()
    {
    	typedef std::multiset<std::string> STRING_MULTI_SET_TYPE ;
    
    	STRING_MULTI_SET_TYPE multisetStrings ;
    
    	multisetStrings.insert("Rohan") ;
    	multisetStrings.insert("Kim") ;
    	multisetStrings.insert("Barbara") ;
    	multisetStrings.insert("Roger") ;
    	multisetStrings.insert("Kim") ;
    
    	char szName[100] ;
    	STRING_MULTI_SET_TYPE::const_iterator constItr = multisetStrings.begin() ;
    	for (; constItr != multisetStrings.end() ; constItr++)
    	{ 
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//equal_range in multiset...
    	std::pair<STRING_MULTI_SET_TYPE::iterator, STRING_MULTI_SET_TYPE::iterator> equalrangeItr ;
    	equalrangeItr = multisetStrings.equal_range("Kim") ;
    	constItr = equalrangeItr.first ;
    	for (; constItr != equalrangeItr.second ; constItr++)
    	{
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//delete item from multiset...
    	STRING_MULTI_SET_TYPE::iterator itr = multisetStrings.begin() ;
    	for (; itr != multisetStrings.end() ;)
    	{
    		if("Kim" == *itr)
    		{
    			multisetStrings.erase(itr++) ;
    		}
    		else
    		{
    			++itr ;
    		}
    	}
    
    	constItr = multisetStrings.begin() ;
    	for (; constItr != multisetStrings.end() ; constItr++)
    	{ 
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//multiset has find member function as it is associative container.
    	constItr = multisetStrings.find("Roger") ;
    	if (constItr != multisetStrings.end())
    	{
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    	else
    	{
    		sprintf(szName, "There is no item present named \"Four\"") ;
    	}
    
    	//clear all the items from multiset
    	multisetStrings.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