fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <numeric>
  4.  
  5. template<typename T>
  6. class Cart {
  7. private:
  8. std::vector<T> items;
  9.  
  10. public:
  11. Cart(const std::vector<T>& v): items(v) { }
  12.  
  13. std::vector<T>& getItems() { return items; }
  14. const std::vector<T>& getItems() const { return items; }
  15. int total() const { return std::accumulate(items.begin(), items.end(), 0); }
  16. };
  17.  
  18. int main() {
  19. std::vector<unsigned int> contents;
  20. Cart<unsigned int> cart(contents);
  21.  
  22. std::cout << "Initial total " + std::to_string(cart.total()) << std::endl;
  23.  
  24. cart.getItems().push_back(10);
  25. cart.getItems().push_back(11);
  26. cart.getItems().push_back(21);
  27.  
  28. std::cout << "New total: " + std::to_string(cart.total()) << std::endl;
  29. return 0;
  30. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Initial total 0
New total:    42