+ Reply to Thread
Results 1 to 2 of 2

Thread: What is function object. How to use it in C++?

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    26

    What is function object. How to use it in C++?

    What is function object. How to use it in C++?

    Please give me simple example of it in C++ using STL container.

  2. #2
    Function object is a function or a class with () operator implemented.

    It can be useful wherever STL method needs predicate.

    Following is an example:

    Code:
    class CComparator
    {
    private:
    	int m_nData ;
    public:
    	CComparator(int nData)
    	{
    		m_nData = nData ;
    	}
    
    	bool operator () (int nData)
    	{
    		if (nData == m_nData)
    		{
    			return true ;
    		}
    
    		return false ;
    	}
    } ;
    
    
    void UseFunObj()
    {
    	std::vector<int> vecInts ;
    
    	vecInts.push_back(10) ;
    	vecInts.push_back(20) ;
    	vecInts.push_back(30) ;
    	vecInts.push_back(40) ;
    	vecInts.push_back(50) ;
    
    	std::vector<int>::iterator itr = std::find_if(vecInts.begin(), vecInts.end(), CComparator(20)) ;
    
    	if (itr != vecInts.end())
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "Data = %d\n", *itr) ;
    		OutputDebugString(szMessage) ;
    	}
    }
    Enjoy!

+ 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