fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Object {
  6. public:
  7. virtual ~Object() {}
  8. };
  9.  
  10. struct Integer : public Object {
  11. int value;
  12.  
  13. Integer(int value) : value(value) {}
  14. };
  15.  
  16. struct MyVector : public std::vector<Object*>, public Object {
  17. MyVector(std::initializer_list<int> list) {
  18. for (const auto& elem : list) {
  19. this->push_back(new Integer(elem));
  20. }
  21. }
  22.  
  23. MyVector(std::initializer_list<MyVector> list) {
  24. for (const auto& elem : list) {
  25. this->push_back(new MyVector(elem));
  26. }
  27. }
  28. };
  29.  
  30. bool getSum_internal(Object &o, int &sum) {
  31. Integer* box = dynamic_cast<Integer*>(&o);
  32. if (box == nullptr) {
  33. MyVector* container = dynamic_cast<MyVector*>(&o);
  34. if (container == nullptr) {
  35. // no idea what type this is so return with error
  36. return false;
  37. }
  38. for (const auto& elem : *container) {
  39. if (getSum_internal(*elem, sum) == false) {
  40. return false;
  41. }
  42. }
  43. return true;
  44. } else {
  45. sum += box->value;
  46. return true;
  47. }
  48. }
  49.  
  50. int getSum(Object &o) {
  51. int sum = 0;
  52. getSum_internal(o, sum);
  53. return sum;
  54. }
  55.  
  56. int main() {
  57. // to construct somth like that: [1,2, [3, [4,5], 6], 7]
  58. MyVector o1({ 1, 2 });
  59. MyVector o2({ 3 });
  60. MyVector o3({ 4, 5 });
  61. MyVector o4({ 6 });
  62. MyVector o5({ o2, o3, o4 });
  63. MyVector o6({ 7 });
  64. MyVector o({ o1, o5, o6 });
  65.  
  66. cout << getSum(o) << endl;
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
28