Advertisement
Lesnic

ITP exceptions 1 my

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