CPP   26
vector generation
Guest on 7th February 2023 02:08:22 AM


  1. #include <iostream>
  2. #include <cassert>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. class U {
  7. public:
  8.   unsigned long id;
  9.   unsigned long generation;
  10.   static unsigned long total_copies;
  11.   U() : id(0), generation(0) { }
  12.   U(unsigned long n) : id(n), generation(0) { }
  13.   U(const U& z) : id(z.id), generation(z.generation + 1) {
  14.     ++total_copies;
  15.   }
  16. };
  17.  
  18. bool operator==(const U& x, const U& y)
  19. {
  20.   return x.id == y.id;
  21. }
  22.  
  23. bool operator!=(const U& x, const U& y)
  24. {
  25.   return x.id != y.id;
  26. }
  27.  
  28. unsigned long U::total_copies = 0;
  29.  
  30. int main()
  31. {
  32.   cout << "Demonstrating STL vector constructors with "
  33.        << "a user-defined type and showing copying "
  34.        << "explicitly" << endl;
  35.   vector<U> vector1, vector2(3);
  36.  
  37.   assert (vector1.size() == 0);
  38.   assert (vector2.size() == 3);
  39.  
  40.   assert (vector2[0] == U() && vector2[1] == U() &&
  41.           vector2[2] == U());
  42.  
  43.   for (int i = 0; i != 3; ++i)
  44.     cout << "vector2[" << i << "].generation: "
  45.          << vector2[i].generation << endl;
  46.  
  47.   cout << "Total copies: " << U::total_copies << endl;
  48.   return 0;
  49. }

Raw Paste

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