Advertisement
PaweU

zad2 cpp

Mar 5th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Array
  5. {
  6.     int *tab;
  7.     int length;
  8.  
  9.     // bez dynamicznej alokacji i konstruktora
  10.     // static const int tabsize = 5;
  11.     // int tab [length];
  12.  
  13.     void check_errors (int index){
  14.       if (index >= length || index < 0){
  15.           cerr << endl << "Bledna wartosc. Podano indeks "<<index<<", a zakres indeksow tablicy to [0-"<<length-1<<"]"<<endl;
  16.           exit(1);
  17.       }
  18.     }
  19. public:
  20.     Array(int liczba){
  21.         length = liczba;
  22.         tab = new int[liczba];
  23.         int i;
  24.         for (i=0; i<liczba; i++){
  25.             tab[i] = i*i;
  26.         }
  27.     }
  28.  
  29.     void set(int index, int value){
  30.         check_errors(index);
  31.         tab[index] = value;
  32.     }
  33.  
  34.     int get(int index){
  35.         check_errors(index);
  36.         return *(tab+index);
  37.     }
  38.  
  39.     const int * front() const{
  40.         return tab;
  41.     }
  42.  
  43.     const int *back() const{
  44.         return &tab[length-1];
  45.     }
  46.  
  47.     int size() const{
  48.         return length;
  49.     }
  50.  
  51.     void clean_up(){
  52.       delete [] tab;
  53.     }
  54.  
  55.     void fill(int value){
  56.       for (int i=0; i< length; i++){
  57.         tab[i] = value;
  58.       }
  59.     }
  60.  
  61.     void assign(const int t[], int tabSize){
  62.       if (tabSize > length) {
  63.         cerr << "Blad. Tablica za dluga." << endl;
  64.         exit(1);
  65.       }
  66.       for (int i=0; i<tabSize; i++) {
  67.       tab[i] = t[i];
  68.       }
  69.     }
  70.  
  71.     Array* clone() const
  72.     {
  73.       Array* tab2 = new Array;
  74.       tab2->assign(tab, length);
  75.       return tab2;
  76.     }
  77.  
  78. };
  79.  
  80. int main()
  81. {
  82.   const int tablica [] = {1,2,3,4,5};
  83.   int ilosc;
  84.   cout << "Podaj wielkosc tablicy: ";
  85.   cin >> ilosc;
  86.   Array arr(ilosc);
  87.   // CIEKAWOSTKA: auto = daje typ taki jaki zwraca funkcja
  88.   auto x = arr.size();
  89.   cout << "Ilosc elementow: " << x << endl;
  90.   arr.set(0, 5);
  91.   arr.set(1, 151515);
  92.   for (int i=0; i<x; i++) cout<<arr.get(i)<<" ";
  93.   const int *p = arr.back();
  94.   cout << endl << "Ostatni element tablicy:" << *p << endl;
  95.   arr.assign(tablica, 5);
  96.   for (int i=0; i<x; i++) cout<<arr.get(i)<<" ";
  97.   auto a2 = arr.clone();
  98.   cout << a2->get(1) << endl;
  99.   arr.clean_up();
  100.   return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement