Use mem_fun_ref to pass in a user-defined member function : mem_fun_ref « STL Algorithms Helper « C++






Use mem_fun_ref to pass in a user-defined member function

  
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <string>
#include <vector>

using namespace std;

class PC
{
   public:
   enum part { keyboard, mouse, monitor };

   PC( part a_part = PC::keyboard, int id = 0 );
   bool operator<( const PC& rhs ) const;

   void print() const;

   private:
   part part_;
   int id_;
};

inline
PC::PC( part a_part, int id ) : part_( a_part ), id_( id ){}

inline bool PC::operator<( const PC& rhs ) const{  
   return id_ < rhs.id_; 
}

void PC::print() const {
   string component;
   if( part_ == keyboard )
      component = "keyboard";
   else if( part_ == mouse )
      component = "mouse";
   else
      component = "monitor";

   cout << "ID: " << setw( 8 ) << left << id_ << " PC: " << component << endl;
}

int main( )
{
   list<PC> listA;
   listA.push_back( PC( PC::keyboard, 3 ) );
   listA.push_back( PC( PC::mouse, 1 ) );
   listA.push_back( PC( PC::monitor, 9 ) );
   listA.push_back( PC( PC::keyboard, 2 ) );
   listA.push_back( PC( PC::monitor, 8 ) );

   for_each( listA.begin(), listA.end(),mem_fun_ref( &PC::print ) );
}
  
    
  








Related examples in the same category

1.mem_fun_ref with method from user-defined class