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

vector2[0].generation: 1
vector2[1].generation: 1
vector2[2].generation: 1
Total copies: 3