Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* TP_Tutorijal_6 Zadatak_4 */
- #include <iostream>
- #include <stdexcept>
- #include <vector>
- using std::cin;
- using std::cout;
- using std::endl;
- template <typename tip>
- void DealocirajMatricu(tip** p, int n) {
- for(int i = 0; i < n; i++)
- delete [] p[i]; // unistava redove
- delete [] p; // unistava niz pokazivaca na redove
- }
- template <typename tip>
- tip** AlocirajMatricu(std::vector<std::vector<tip>> &v) {
- // FRAGMENTIRANA ALOKACIJA
- tip** p = new tip*[v.size()];
- for(int i = 0; i < v.size(); i++)
- p[i] = nullptr;
- try {
- for(int i = 0; i < v.size(); i++) {
- p[i] = new int[v[i].size()];
- for(int j = 0; j < v[i].size(); j++) {
- p[i][j] = v[i][j];
- }
- }
- }
- catch(std::bad_alloc) {
- cout << "Alokacija nije uspjela." << endl;
- DealocirajMatricu(p, v.size());
- throw std::bad_alloc();
- }
- return p;
- }
- int main()
- {
- try {
- std::vector<std::vector<int>> v{{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};
- auto matrica = AlocirajMatricu(v);
- cout << "Elementi matrice su:" << endl;
- for(int i = 0; i < v.size(); i++) {
- for(int j = 0; j < v[i].size(); j++)
- cout << matrica[i][j] << " ";
- cout << endl;
- }
- /* oslobadjanje zauzete memorije alokacijom grbave matrice */
- DealocirajMatricu(matrica, v.size());
- }
- catch(std::bad_alloc) {
- cout << "Alokacija nije uspjela." << endl;
- }
- catch(std::domain_error izuzetak) {
- cout << izuzetak.what() << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement