Advertisement
FRiTZZY

TP_T6_Z4

Apr 18th, 2015
642
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. /* TP_Tutorijal_6 Zadatak_4 */
  2. #include <iostream>
  3. #include <stdexcept>
  4. #include <vector>
  5.  
  6. using std::cin;
  7. using std::cout;
  8. using std::endl;
  9.  
  10. template <typename tip>
  11. void DealocirajMatricu(tip** p, int n) {
  12.     for(int i = 0; i < n; i++)
  13.         delete [] p[i]; // unistava redove
  14.     delete [] p; // unistava niz pokazivaca na redove
  15. }
  16.  
  17. template <typename tip>
  18. tip** AlocirajMatricu(std::vector<std::vector<tip>> &v) {
  19.     // FRAGMENTIRANA ALOKACIJA
  20.     tip** p = new tip*[v.size()];
  21.     for(int i = 0; i < v.size(); i++)
  22.         p[i] = nullptr;
  23.  
  24.     try {
  25.         for(int i = 0; i < v.size(); i++) {
  26.             p[i] = new int[v[i].size()];
  27.             for(int j = 0; j < v[i].size(); j++) {
  28.                 p[i][j] = v[i][j];
  29.             }
  30.         }
  31.     }
  32.     catch(std::bad_alloc) {
  33.         cout << "Alokacija nije uspjela." << endl;
  34.         DealocirajMatricu(p, v.size());
  35.         throw std::bad_alloc();
  36.     }
  37.  
  38.     return p;
  39. }
  40.  
  41. int main()
  42. {
  43.     try {
  44.         std::vector<std::vector<int>> v{{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};
  45.         auto matrica = AlocirajMatricu(v);
  46.         cout << "Elementi matrice su:" << endl;
  47.         for(int i = 0; i < v.size(); i++) {
  48.             for(int j = 0; j < v[i].size(); j++)
  49.                 cout << matrica[i][j] << " ";
  50.             cout << endl;
  51.         }
  52.         /* oslobadjanje zauzete memorije alokacijom grbave matrice */
  53.         DealocirajMatricu(matrica, v.size());
  54.     }
  55.     catch(std::bad_alloc) {
  56.         cout << "Alokacija nije uspjela." << endl;
  57.     }
  58.     catch(std::domain_error izuzetak) {
  59.         cout << izuzetak.what() << endl;
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement