Created
January 8, 2015 22:45
-
-
Save miensol/759ebe1e4733b71537b9 to your computer and use it in GitHub Desktop.
Szablony i lista
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <class T> | |
class Lista { | |
unsigned int rozmiarTablicy; | |
unsigned int liczbaElementow; | |
T* elementy; | |
public: | |
Lista() { | |
elementy = new T[1]; | |
rozmiarTablicy = 1; | |
liczbaElementow = 0; | |
} | |
void dodajElement(T element){ | |
przepakujJesliZaMaloMiejsca(1); | |
elementy[liczbaElementow] = element; | |
liczbaElementow += 1; | |
} | |
void dodajWszystkie(Lista<T>& inna){ | |
for(auto &element:inna){ | |
dodajElement(element); | |
} | |
} | |
unsigned int size(){ | |
return liczbaElementow; | |
} | |
T* begin(){ | |
if(liczbaElementow == 0){ | |
return NULL; | |
} | |
return &elementy[0]; | |
} | |
T* end(){ | |
if(liczbaElementow == 0){ | |
return NULL; | |
} | |
return &elementy[liczbaElementow]; | |
} | |
virtual ~Lista() { | |
free(elementy); | |
} | |
private: | |
void przepakujJesliZaMaloMiejsca(int liczbaElementowDododania){ | |
while(liczbaElementow + liczbaElementowDododania > rozmiarTablicy){ | |
int nowyRozmiarTablicy = rozmiarTablicy*2; | |
T*nowaLista = new T[nowyRozmiarTablicy]; | |
for(int index=0; index<rozmiarTablicy; index +=1){ | |
nowaLista[index] = elementy[index]; | |
} | |
free(elementy); | |
elementy = nowaLista; | |
rozmiarTablicy = nowyRozmiarTablicy; | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "lista.h" | |
using namespace std; | |
template<class T> void wypiszElementy(Lista<T> &lista, std::string napis){ | |
for(T &element:lista){ | |
cout << napis << " " << element << endl; | |
} | |
cout << napis << " liczba elementow: " << lista.size() << endl; | |
} | |
int main() { | |
cout << "Hello, World!" << endl; | |
Lista<int> ints; | |
wypiszElementy(ints, "pusta lista"); | |
ints.dodajElement(1); | |
ints.dodajElement(2); | |
ints.dodajElement(3); | |
ints.dodajElement(4); | |
wypiszElementy(ints, "4 elementy"); | |
Lista<int> inna; | |
inna.dodajWszystkie(ints); | |
wypiszElementy(ints, "inna a ma wszystkie"); | |
for(int element:inna){ | |
cout << "A tutaj sobie iteruje normalnie " << element << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment