keep only the top 3 salespeople : list erase « List « C++






keep only the top 3 salespeople

  
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>

using namespace std;

class Employee
{
   public:
   Employee( const string& name = "", int sales = 0,int district = 0 );
   bool operator>( const Employee& rhs ) const;
   void print() const;

   private:
   int district_;
   string name_;
   int sales_;
};

inline
Employee::Employee( const string& name, int sales,
   int district )
   : district_( district ), name_( name ), sales_( sales )
{} 

inline
bool Employee::operator>( const Employee& rhs ) const
{ return sales_ > rhs.sales_; }

inline
void Employee::print() const
{ cout << name_ << " from District " << district_
   << " has sales of $" << sales_ << endl;
}

int main( )
{
   list<Employee> list1;
   list1.push_back( Employee( "A", 3, 1 ) );
   list1.push_back( Employee( "B", 4, 1 ) );
   list1.push_back( Employee( "C", 8, 1 ) );

   list1.sort( greater<Employee>() );
   for_each( list1.begin(), list1.end(), mem_fun_ref( &Employee::print ) );

   const int top_positions = 3;
   list<Employee>::iterator position = list1.begin();
   advance( position, top_positions );
   list1.erase( position, list1.end() );

   for_each( list1.begin(), list1.end(),mem_fun_ref( &Employee::print ) );

}
  
    
  








Related examples in the same category

1.Demonstrating the STL list erase function