sort list with user-defined objects with greater : list sort « list « C++ Tutorial

Home
C++ Tutorial
1.Language Basics
2.Data Types
3.Operators statements
4.Array
5.Development
6.Exceptions
7.Function
8.Structure
9.Class
10.Operator Overloading
11.Pointer
12.File Stream
13.template
14.STL Introduction
15.string
16.vector
17.list
18.bitset
19.set multiset
20.valarray
21.queue stack
22.deque
23.map multimap
24.STL Algorithms Modifying sequence operations
25.STL Algorithms Non modifying sequence operations
26.STL Algorithms Binary search
27.STL Algorithms Sorting
28.STL Algorithms Merge
29.STL Algorithms Min Max
30.STL Algorithms Iterator
31.STL Algorithms Heap
32.STL Algorithms Helper
C / ANSI-C
C Tutorial
C++
Visual C++ .NET
C++ Tutorial » list » list sort 
17.14.3.sort list with user-defined objects with greater
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>

using namespace std;

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

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

inline
Salesperson::Salespersonconst string& name, int sales,
   int district )
   : district_district ), name_name ), sales_sales )
{} 

inline
bool Salesperson::operator>const Salesperson& rhs const
return sales_ > rhs.sales_; }

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

int main( )
{
   list<Salesperson> list1;
   list1.push_backSalesperson"A"37000) );
   list1.push_backSalesperson"B"49000) );
   list1.push_backSalesperson"C"48500) );

   // sort District 1 salespeople in descending order and display
   list1.sortgreater<Salesperson>() );
   for_eachlist1.begin(), list1.end(), mem_fun_ref&Salesperson::print ) );

   list<Salesperson> list2;
   list2.push_backSalesperson"A"65000) );
   list2.push_backSalesperson"B"33000) );
   list2.push_backSalesperson"C"47000) );

   // sort District 2 salespeople in descending order and display
   list2.sortgreater<Salesperson>() );
   for_eachlist2.begin(), list2.end(), mem_fun_ref&Salesperson::print ) );

}
17.14.list sort
17.14.1.Sort a list
17.14.2.sort objects in a list
17.14.3.sort list with user-defined objects with greater
17.14.4.Sorting a List of Integers in Ascending and Descending Order
17.14.5.Sorting user-defined objects in list by its properties
17.14.6.list.sort()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.