1
0
Fork 0
This repository has been archived on 2021-11-03. You can view files and clone it, but cannot push or open issues or pull requests.
uni-m.cds-adv-prog/ex6.2/Array.hh

78 lines
1.3 KiB
C++
Raw Normal View History

2019-12-03 13:50:25 +01:00
#ifndef ARRAY_HH
#define ARRAY_HH
2020-01-06 13:28:39 +01:00
template<class T>
2019-12-03 13:50:25 +01:00
class Array {
public:
2020-01-06 13:28:39 +01:00
Array(int size, T default_value) : _size(size) {
_arr = new T[_size] ;
_default = default_value;
2019-12-03 13:50:25 +01:00
}
Array(const Array& other) : _size(other._size) {
2020-01-06 13:28:39 +01:00
_arr = new T[other._size] ;
2019-12-03 13:50:25 +01:00
// Copy elements
for (int i=0 ; i<_size ; i++) {
_arr[i] = other._arr[i] ;
}
}
~Array() {
delete[] _arr ;
}
Array& operator=(const Array& other)
{
if (&other==this) return *this ;
if (_size != other._size) {
resize(other._size) ;
}
for (int i=0 ; i<_size ; i++) {
_arr[i] = other._arr[i] ;
}
return *this ;
}
2020-01-06 13:28:39 +01:00
T& operator[](int index) {
if ( index > _size ) {
resize(index+1);
}
2019-12-03 13:50:25 +01:00
return _arr[index] ;
}
2020-01-06 13:28:39 +01:00
const T& operator[](int index) const {
2019-12-03 13:50:25 +01:00
return _arr[index] ;
}
int size() const { return _size ; }
void resize(int newSize) {
// Allocate new array
2020-01-06 13:28:39 +01:00
T* newArr = new T[newSize] ;
2019-12-03 13:50:25 +01:00
// Copy elements
for (int i=0 ; i<_size ; i++) {
newArr[i] = _arr[i] ;
}
2020-01-06 13:28:39 +01:00
for ( int i=_size ; i<newSize ; i++ ) {
newArr[i] = _default;
}
2019-12-03 13:50:25 +01:00
// Delete old array and install new one
delete[] _arr ;
_size = newSize ;
_arr = newArr ;
}
private:
int _size ;
2020-01-06 13:28:39 +01:00
T* _arr ;
T _default ;
2019-12-03 13:50:25 +01:00
} ;
#endif