CPP   27
less with count
Guest on 7th February 2023 02:09:34 AM


  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cassert>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <functional>
  7. using namespace std;
  8. template <typename T>
  9. class less_with_count : public binary_function<T, T, bool> {
  10. public:
  11.   less_with_count() : counter(0), progenitor(0) { }
  12.   // Copy constructor:
  13.   less_with_count(less_with_count<T>& x) : counter(0),
  14.       progenitor(x.progenitor ? x.progenitor : &x) { }
  15.   bool operator()(const T& x, const T& y) {
  16.     ++counter;
  17.     return x < y;
  18.   }
  19.   long report() const { return counter; }
  20.   ~less_with_count() {  // Destructor
  21.     if (progenitor) {
  22.       progenitor->counter += counter;
  23.     }
  24.   }
  25. private:
  26.   long counter;
  27.   less_with_count<T>* progenitor;
  28. };
  29. int main()
  30. {
  31.   cout << "Using a function object for operation counting, "
  32.        << "second version." << endl;
  33.   const long N1 = 1000, N2 = 128000;
  34.   for (long N = N1; N <= N2; N *= 2) {
  35.     vector<int> vector1;
  36.     for (int k = 0; k < N; ++k)
  37.       vector1.push_back(k);
  38.     random_shuffle(vector1.begin(), vector1.end());
  39.     less_with_count<int> comp_counter;
  40.     sort(vector1.begin(), vector1.end(), comp_counter);
  41.     cout << "Problem size " << setw(9) << N
  42.          << ",  comparisons performed: "
  43.          << setw(9) << comp_counter.report() << endl;
  44.   }
  45.   return 0;
  46. }

Raw Paste

Login or Register to edit or fork this paste. It's free.