Commit 88f2cbc7 by Patryk Czarnik

tablica dynamiczna: new i delete

parent 341f8685
#include <iostream>
#include "wektor.h"
const int startowy_rozmiar_tablicy = 8;
Wektor::Wektor()
: liczba_elementow{0}
{}
: rozmiar_tablicy{startowy_rozmiar_tablicy},
liczba_elementow{0}
{
t = new int[rozmiar_tablicy];
}
Wektor::~Wektor() {
delete[] t;
}
int Wektor::size() {
int Wektor::size() const {
return liczba_elementow;
}
void Wektor::push_back(int e) {
t[liczba_elementow] = e;
liczba_elementow++;
if(liczba_elementow == rozmiar_tablicy) {
// przerzuć elementy do większej tablicy
rozmiar_tablicy = 2*rozmiar_tablicy;
int *nt = new int[rozmiar_tablicy];
for(int i=0; i<liczba_elementow; i++) {
nt[i] = t[i];
}
delete[] t;
t = nt; // do t wpisujemy wskaźnik do nowe tablicy
}
t[liczba_elementow++] = e;
}
void Wektor::set(int idx, int e) {
......
......@@ -5,7 +5,10 @@
/** Tablica zmiennej długości zawierająca wartości int. */
class Wektor {
int t[10];
int *t;
// fizyczny rozmiar wewnętrznej tablicy
int rozmiar_tablicy;
// logiczny rozmiar wektora = ile pozycji w tablicy jest zajętych = indeks pierwszej wolnej pozycji
int liczba_elementow;
......@@ -15,7 +18,7 @@ public:
~Wektor();
int size();
int size() const;
/** Dodanie nowego elementu na końcu. */
void push_back(int e);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment