Advertisement
Guest User

Two-level sort

a guest
Mar 31st, 2010
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <list>
  2. #include <utility>
  3. #include <iostream>
  4.  
  5. typedef std::pair<char, int> PAIR;
  6.  
  7. // NOTE: the Key() virtual methods use the first letter
  8. //       of the class (b,c,g) as the first pair member since
  9. //       they are (conveniently) already sorted alphabetically.
  10. //       Were this not the case, any other sorted choice would work.
  11.  
  12. // Question 1: Should Grandchild also have an id/val?
  13. // Question 2: How do we sort amongst Grandchildren?
  14. // ANYWAY....
  15.  
  16. class BaseObject
  17. {
  18.  public:
  19.    BaseObject(int i) : id(i) {}
  20.    virtual PAIR Key() const {return(std::make_pair('b', id));}
  21.    virtual ~BaseObject() {}
  22.  private:
  23.    int id;
  24. };
  25.  
  26.  
  27. class Child : public BaseObject
  28. {
  29.  public:
  30.    Child(int id1, int n) : BaseObject(id1), var(n) {}
  31.    virtual PAIR Key() const {return(std::make_pair('c', var));}
  32.    virtual ~Child() {}
  33.  private:
  34.    int var;
  35. };
  36.  
  37. class GrandChild : public Child
  38. {
  39.  public:
  40.    GrandChild(int id1, int n) : Child(id1,n) {};
  41.    virtual PAIR Key() const {return(std::make_pair('g', 0));}
  42.    virtual ~GrandChild() {}
  43. };
  44.  
  45.  
  46. struct Comparator
  47. {
  48.    bool operator()(const BaseObject* o1, const BaseObject* o2) const
  49.    {
  50.        // std::pair already has built-in comparison
  51.        return (o1->Key() < o2->Key());
  52.    }
  53. };
  54.  
  55. typedef std::list<BaseObject*>                  MYLIST;
  56. typedef std::list<BaseObject*>::const_iterator  ITER;
  57.  
  58. int main()
  59. {
  60.  // TODO: Deletes, exception handling, etc.
  61.  MYLIST mylist;
  62.  
  63.  // Build the list...
  64.  // Bases sorted before Children; Children sorted before Grandchildren
  65.  // Within a class, the id/var/etc. is used to sort.
  66.  
  67.  mylist.push_back(new BaseObject(99));
  68.  mylist.push_back(new BaseObject(98));
  69.  mylist.push_back(new Child(50, 22));
  70.  mylist.push_back(new Child(98, 21));
  71.  mylist.push_back(new Child(99, 20));
  72.  mylist.push_back(new GrandChild(50, 40));
  73.  mylist.push_back(new GrandChild(98, 35));
  74.  
  75.  // Sort the list using our Comparator
  76.  mylist.sort(Comparator());
  77.  
  78.  // Output (display) the sorted list
  79.  ITER pos;
  80.  for (pos = mylist.begin(); pos != mylist.end(); ++pos)
  81.  {
  82.    PAIR p = (*pos)->Key();
  83.    std::cout << p.first << " " << p.second << std::endl;
  84.  }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement