+ Reply to Thread
Results 1 to 2 of 2

Thread: What is unary_function? How to use it?

  1. #1

    What is unary_function? How to use it?

    What is unary_function? How to use it?

  2. #2
    unary_function can be used to create unary predicate. Which takes single argument and return true or false based on your requirement.

    Example;

    Code:
    #include <algorithm>
    #include <functional>
    #include <vector>
    
    template<typename T1, typename T2>
    struct CComparator : std::unary_function<T1, T2>
    {
    	int m_nReferenceValue ;
    	
    	CComparator()
    	{
    	}
    
    	CComparator(int nReferenceValue)
    	{
    		m_nReferenceValue = nReferenceValue ;
    	}
    	
    	T2 operator()(T1 nCurrentValue) const
    	{
    		if(nCurrentValue >= m_nReferenceValue)
    		{
    			return true ;
    		}
    
    		return false ;
    	}
    } ;
    
    void UseUnaryFunction()
    {
    	typedef std::vector<int>			VECTOR_INT_TYPE ;
    	typedef std::vector<int>::iterator	VECTOR_INT_ITR_TYPE ;
    
    	VECTOR_INT_TYPE vIntLists ;
    
    	vIntLists.push_back(1) ;
    	vIntLists.push_back(2) ;
    	vIntLists.push_back(42) ;
    	vIntLists.push_back(31) ;
    	vIntLists.push_back(18) ;
    	vIntLists.push_back(310) ;
    
    	VECTOR_INT_ITR_TYPE itr = std::find_if(vIntLists.begin(), vIntLists.end(), CComparator<int, bool>(42)) ;
    
    	if(itr != vIntLists.end())
    	{
    		int nValue = *itr ;
    	}
    }

+ 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