mem_fun_ref with method from user-defined class
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
class Employee
{
public:
Employee( string name = "Unknown", int income = 0, int bonus_percentage = 0 );
int bonus( int games_won ) const;
void print() const;
string name() const;
int income() const;
private:
int salary() const;
int bonus_percentage_;
int income_;
string name_;
};
inline Employee::Employee(string name, int income, int bonus_percentage): bonus_percentage_( bonus_percentage ), income_( income ),name_( name )
{}
inline int Employee::bonus( int games_won ) const{
return static_cast<int>(salary() * ( bonus_percentage_ / 100.0 ) * games_won );
}
inline
void Employee::print() const
{
cout << setw( 10 ) << left << name() << "Income: " << setw( 8 )
<< right << income() << " euro per year Bonus: "
<< bonus_percentage_ << "% of salary per game won\n";
}
inline int Employee::income() const
{ return income_; }
inline
string Employee::name() const
{ return name_; }
inline
int Employee::salary() const
{ return static_cast<int>( 0.3 * income() ); }
int main( ){
vector<Employee> myVector;
myVector.push_back( Employee( "A", 4, 3 ) );
myVector.push_back( Employee( "B", 1, 3 ) );
myVector.push_back( Employee( "C", 2, 3 ) );
myVector.push_back( Employee( "D", 3, 2 ) );
myVector.push_back( Employee( "E", 5, 1 ) );
for_each( myVector.begin(), myVector.end(),mem_fun_ref( &Employee::print ) );
vector<int> temporary( myVector.size() );
transform( myVector.begin(), myVector.end(),temporary.begin(), mem_fun_ref( &Employee::income ) );
int average_income = accumulate( temporary.begin(),temporary.end(), 0 ) / temporary.size();
cout << myVector.size()
<< " : "
<< average_income << " \n\n";
}
Related examples in the same category