fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <stdexcept>
  4. #include <limits>
  5.  
  6. using namespace std;
  7.  
  8. // ----------------------------------------------------------------------------
  9. struct Entry {
  10. string name;
  11. int number;
  12. };
  13.  
  14. // ----------------------------------------------------------------------------
  15. template<typename T>
  16. class Vec : public std::vector<T> {
  17.  
  18. public:
  19. // TO DO : I d not understand the next statement
  20. // See http://w...content-available-to-author-only...p.com/what-is-2009.pdf
  21. // This means "import" vector() (constructors) from std::vector
  22. // Inheriting constructors
  23. using vector<T>::vector; // use the constructors from vector (under the name Vec). There is a typo in the book
  24. T& operator[](int i) // range check
  25. {
  26. return vector<T>::at(i);
  27. }
  28.  
  29. const T& operator[](int i) const // range check const objects; ยง4.2.1
  30. {
  31. return vector<T>::at(i);
  32. }
  33. };
  34.  
  35.  
  36. // ----------------------------------------------------------------------------
  37. void checked(Vec<Entry>& book)
  38. {
  39. try {
  40. book[book.size()] = { "Joe", 999999 }; // will throw an exception
  41. // ...
  42. }
  43. catch (out_of_range) {
  44. cout << "range error\n";
  45. }
  46. }
  47.  
  48. // ----------------------------------------------------------------------------
  49. void Test(void) {
  50.  
  51. Vec<Entry> MyBook;
  52. checked(MyBook);
  53.  
  54.  
  55. }
  56.  
  57. // ----------------------------------------------------------------------------
  58. int main() {
  59.  
  60.  
  61. Test();
  62.  
  63. cout << "Press ENTER to quit : ";
  64. cin.ignore((numeric_limits<streamsize>::max)(), '\n');
  65. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
range error
Press ENTER to quit :