fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. template <typename T> class foo
  6. {
  7. T attribute1;
  8. std::vector<foo*> attribute2;
  9.  
  10. public:
  11. foo(const T& data):attribute1(data){}
  12.  
  13. // Some methods
  14.  
  15. foo* getAttribute2(int pos)const
  16. {
  17. if (pos<0 || pos>=attribute2.size())
  18. throw "In foo::getAttribute2, argument out of range";
  19. return attribute2[pos];
  20. }
  21. void append(foo<T>* element) {attribute2.push_back(element);}
  22.  
  23. void foo2vector(std::vector<T>& v) const
  24. {
  25. v.push_back(attribute1);
  26. if (attribute2.size()>0)
  27. {
  28. for(int i=0; i<attribute2.size();i++)
  29. attribute2[i]->foo2vector(v);
  30. }
  31. }
  32.  
  33. void display3()const
  34. {
  35. std::vector<T> v;
  36. foo2vector(v);
  37. std::reverse(v.begin(),v.end());
  38. for (int i=0;i<v.size();i++)
  39. std::cout<<v[i]<<"\t";
  40. }
  41.  
  42. };
  43.  
  44. int main()
  45. {
  46. foo<int>* root=new foo<int>(12);
  47. root->append(new foo<int>(8)); // node 0
  48. root->append(new foo<int>(23)); // node 1
  49. // Sons of node 0
  50. (root->getAttribute2(0))->append(new foo<int>(4));
  51. (root->getAttribute2(0))->append(new foo<int>(9));
  52. // Sons of node 1
  53. (root->getAttribute2(1))->append(new foo<int>(17)); // node 4
  54. root->display3();
  55. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
17	23	9	4	8	12