Lesnic

ITP exceptions 1 first

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