Advertisement
Lesnic

ITP exceptions 1 second

Apr 11th, 2020
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class LengthsNotEqualException : exception {
  6. public:
  7.     LengthsNotEqualException() {
  8.     }
  9.  
  10.     const char* what() const noexcept {
  11.         return "The lengths of two containers are not equal";
  12.     }
  13. };
  14.  
  15. class Container {
  16. private:
  17.     int lenght;
  18.     int* arr;
  19.  
  20. public:
  21.     Container() {
  22.         cin >> lenght;
  23.         arr = new int[lenght];
  24.         for (int i = 0; i < lenght; i++)
  25.             cin >> arr[i];
  26.     }
  27.  
  28.     friend int dot_product(Container& a, Container& b) {
  29.         if (a.lenght != b.lenght)
  30.             throw LengthsNotEqualException();
  31.  
  32.         int c = 0;
  33.         for (int i = 0; i < a.lenght; i++)
  34.             c += a.arr[i] * b.arr[i];
  35.         return c;
  36.     }
  37. };
  38.  
  39. int main()
  40. {
  41.     Container a, b;
  42.  
  43.     try {
  44.         cout << dot_product(a, b);
  45.     }
  46.     catch (LengthsNotEqualException & exception){
  47.         cout << exception.what();
  48.     }
  49.     catch (exception & exception) {
  50.         cout << exception.what();
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement