Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <exception>
  3.  
  4. template <class T>
  5. T& cool_min(T& a, T& b) {
  6.     return (a < b) ? a : b;
  7. }
  8.  
  9.  
  10. class InvalidIndexException : public std::exception {
  11. public:
  12.     explicit InvalidIndexException(int index) : index_(index) {}
  13.     [[nodiscard]] int Index() const { return index_;}
  14.     const char* what() {
  15.         return "Invalid Index";
  16.     }
  17. private:
  18.     int index_;
  19. };
  20.  
  21.  
  22. template <int N, class T>
  23. class CArray {
  24. public:
  25.     CArray() : arr_(new T[N]), size_(N) {
  26.     }
  27.     [[nodiscard]] int Size() const { return size_;}
  28.     T& operator[] (const int index) {
  29.         if(index < 0 || index >= size_)
  30.             throw InvalidIndexException(index);
  31.         return arr_[index];
  32.     }
  33. private:
  34.     T* arr_;
  35.     int size_;
  36. };
  37.  
  38.  
  39. int main() {
  40.     std::string s1 = "c", s2 = "b";
  41.     cool_min(s1, s2);
  42.     std::cout << cool_min(s1, s2) << "\n";
  43.  
  44.     CArray<5, int> arr;
  45.     arr[4] = 3;
  46.     std::cout << arr[4] << "\n";
  47.     try {
  48.         arr[8] = 123;
  49.     }
  50.     catch(InvalidIndexException &e) {
  51.         std::cout << e.what() << "\n";
  52.         std::cout << "Wrong index = " << e.Index() << "\n";
  53.     }
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement