+ Reply to Thread
Results 1 to 2 of 2

Thread: What is binary_function in C++ STL? How to use it?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    49

    What is binary_function in C++ STL? How to use it?

    What is binary_function in C++ STL? How to use it?

  2. #2
    Binary function is a predicate which takes two argument and return true or false based on the argument.

    Example:

    Code:
    #include <vector>
    #include <functional>
    #include <algorithm>
    class CStudent
    {
    private:
    	int			m_nMarks ;
    	std::string m_strName ;
    public:
    
    	CStudent(const int nMarks, const std::string strName)
    	{
    		m_nMarks	= nMarks ;
    		m_strName	= strName ;
    	}
    
    	int GetMarks()
    	{
    		return m_nMarks	;
    	}
    
    	std::string GetName()
    	{
    		return m_strName ;
    	}
    } ;
    
    
    template<typename T1, typename T2, typename T3>
    class CComparator : public std::binary_function<T1 *, T2 *, T3>
    {
    public:
    	T3 operator()(T1 *pStudent1, T2 *pStudent2) const
    	{
    		if(pStudent1->GetMarks() < pStudent2->GetMarks())
    		{
    			return true ;
    		}
    		return false ;
    	}
    } ;
    
    void UseBinaryPredicate()
    {
    	std::vector<CStudent *> vStudents ;
    
    	vStudents.push_back(new CStudent(546, "Roger")) ;
    	vStudents.push_back(new CStudent(456, "Nathan")) ;
    	vStudents.push_back(new CStudent(390, "Mik")) ;
    	vStudents.push_back(new CStudent(567, "Ovaish")) ;
    	vStudents.push_back(new CStudent(510, "Federer")) ;
    
    	std::vector<CStudent *>::iterator itr = std::max_element(vStudents.begin(), vStudents.end(), CComparator<CStudent, CStudent, bool>()) ;
    
    	if(itr != vStudents.end())
    	{
    		int nHighestMarks = (*itr)->GetMarks() ;
    	}
    }
    Note:
    To know about predicate: http://www.codeexperts.com/showthrea...ight=predicate

+ 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