+ Reply to Thread
Results 1 to 2 of 2

Thread: Using std::set in C++

  1. #1

    Using std::set in C++

    Hi All,

    I am newbie to C++ and want to learn STL library.

    Can anyone provide useful example for Using std::set?

    Regards.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    a. std::set stores item (in sorted order) of specified type that is unique. So item is considered as a key.
    b. If you have more accessing required to the container class than use set as it is considered as fast.
    c. It is normally implemented as binary search tree.

    Code:
    #include <set>
    #include <string>
    #include <iterator>
    #include <algorithm>
    
    void UseVector()
    {
    	typedef std::set<std::string> STRING_SET_TYPE ;
    
    	STRING_SET_TYPE setStrings ;
    
    	setStrings.insert("One") ;
    	setStrings.insert("Two") ;
    	setStrings.insert("Three") ;
    	setStrings.insert("Four") ;
    	setStrings.insert("Five") ;
    
    	//we need const_iterator type to iterate throgh the set items
    	//note: we can see that item comes in sorted order!
    	char szName[100] ;
    	STRING_SET_TYPE::const_iterator constItr = setStrings.begin() ;
    	for (; constItr != setStrings.end() ; constItr++)
    	{ 
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//delete an item from set...
    	STRING_SET_TYPE::iterator itr = setStrings.begin() ;
    	for (; itr != setStrings.end() ;)
    	{
    		if("Four" == *itr)
    		{
    			setStrings.erase(itr++) ;
    		}
    		else
    		{
    			++itr ;
    		}
    	}
    
    	constItr = setStrings.begin() ;
    	for(; constItr != setStrings.end() ; constItr++)
    	{
    		//display item,
    		sprintf(szName, "Item = %s", constItr->c_str()) ;
    	}
    
    	//set has find member function as it is associative container.
    	constItr = setStrings.find("Four") ;
    	if (constItr != setStrings.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 set
    	setStrings.clear() ;
    }
    Note:
    a. std::set is associative contains.

+ 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