home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / ListVsSet.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.3 KB  |  63 lines

  1. //: C20:ListVsSet.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Comparing list and set performance
  7. #include <iostream>
  8. #include <list>
  9. #include <set>
  10. #include <algorithm>
  11. #include <ctime>
  12. #include <cstdlib>
  13. using namespace std;
  14.  
  15. class Obj {
  16.   int a[20];
  17.   int val;
  18. public:
  19.   Obj() : val(rand() % 500) {}
  20.   friend bool 
  21.   operator<(const Obj& a, const Obj& b) {
  22.     return a.val < b.val;
  23.   }
  24.   friend bool 
  25.   operator==(const Obj& a, const Obj& b) {
  26.     return a.val == b.val;
  27.   }
  28.   friend ostream& 
  29.   operator<<(ostream& os, const Obj& a) {
  30.     return os << a.val;
  31.   }
  32. };
  33.  
  34. template<class Container>
  35. void print(Container& c) {
  36.   typename Container::iterator it;
  37.   for(it = c.begin(); it != c.end(); it++)
  38.     cout << *it << " ";
  39.   cout << endl;
  40. }
  41.  
  42. struct ObjGen {
  43.   Obj operator()() { return Obj(); }
  44. };
  45.  
  46. int main() {
  47.   const int sz = 5000;
  48.   srand(time(0));
  49.   list<Obj> lo;
  50.   clock_t ticks = clock();
  51.   generate_n(back_inserter(lo), sz, ObjGen());
  52.   lo.sort();
  53.   lo.unique();
  54.   cout << "list:" << clock() - ticks << endl;
  55.   set<Obj> so;
  56.   ticks = clock();
  57.   generate_n(inserter(so, so.begin()), 
  58.     sz, ObjGen());
  59.   cout << "set:" << clock() - ticks << endl;
  60.   print(lo);
  61.   print(so);
  62. } ///:~
  63.