fork(1) download
  1. #include <string>
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. template <class T>
  6. class Inventory
  7. {
  8. public:
  9. void operator += (const T& b) { backpack.push_back(b); }
  10.  
  11. T operator [] (const unsigned& b)
  12. {
  13. try
  14. {
  15. return backpack.at(b);
  16. }
  17. catch (std::out_of_range& e)
  18. {
  19. throw std::string("Out of Range");
  20. }
  21. }
  22.  
  23. void operator -= (const unsigned& b)
  24. {
  25. try
  26. {
  27. backpack.at(b);
  28. backpack.erase(backpack.begin() + b);
  29. }
  30. catch(std::out_of_range& e)
  31. {
  32. throw std::string("No such element exists.");
  33. }
  34. }
  35.  
  36. private:
  37. std::vector<int> backpack;
  38. };
  39.  
  40. using namespace std;
  41.  
  42. int main()
  43. {
  44. Inventory<int> pack;
  45. pack += 2;
  46. pack += 4;
  47. try
  48. {
  49. cout << "It was " << pack[0] << endl;
  50. cout << "It was " << pack[1] << endl;
  51. pack -= 0;
  52. cout << "It is now " << pack[0] << endl;
  53. pack -= 1; // Segfaults?
  54. }
  55. catch (string e)
  56. {
  57. cout << "Error: " << e << endl;
  58. }
  59. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
It was 2
It was 4
It is now 4
Error: No such element exists.