#include
#include
using namespace std;
class dinamic_array {
public:
dinamic_array()
: length(0), data(nullptr) {}
dinamic_array(const size_t length)
: length(length), data(new(nothrow) int[length]) {
if (data != nullptr) memset(data, 0, length);
else this->length = 0;
}
dinamic_array(const size_t length, int value)
: length(length), data(new(nothrow) int[length]) {
if (data != nullptr) fill(begin(), end(), value);
else this->length = 0;
}
dinamic_array(const initializer_list& ilst)
: length(ilst.size()), data(new(nothrow) int[length]) {
copy(ilst.begin(), ilst.end(), begin());
}
dinamic_array(const dinamic_array& da)
: length(da.size()), data(new(nothrow) int[length]) {
copy(da.begin(), da.end(), begin());
}
dinamic_array(dinamic_array&& da) noexcept
: length(da.size()), data(nullptr) {
data = move(da.data);
da.data = nullptr;
}
~dinamic_array() {
if (data != nullptr) {
delete[] data;
data = nullptr;
}
}
dinamic_array operator=(const dinamic_array& da) {
if (&da != this) {
delete[] data;
length = da.size();
data = new(nothrow) int[length];
if (data != nullptr) copy(da.begin(), da.end(), begin());
else length = 0;
}
return *this;
}
dinamic_array operator=(dinamic_array&& da) noexcept {
if (&da != this) {
length = da.size();
data = move(da.data);
da.data = nullptr;
}
return *this;
}
int& operator[](const size_t i) { return data[i]; }
int& operator[](const size_t i) const { return data[i]; }
void push_back(const int value) {
auto tmp = move(data);
data = nullptr;
data = new int[length + 1];
copy(tmp, tmp + length, begin());
data[length] = value;
++length;
}
void insert(size_t pos, const int value) {
if (pos >= length) push_back(value);
else {
auto tmp = move(data);
data = nullptr;
data = new int[length + 1];
auto ins = copy(tmp, tmp + pos, begin());
*ins = value;
++ins;
copy(tmp + pos, tmp + length, ins);
++length;
}
}
size_t size() const { return length; };
int* begin() { return data; }
int* end() { return data + length; }
int* begin() const { return data; }
int* end() const { return data + length; }
private:
size_t length;
int* data;
friend ostream& operator<<(ostream& out, const dinamic_array& da) {
for (auto value : da) out << value << ' ';
return out;
}
};
int main() {
dinamic_array a(5);
auto n = 0;
for (size_t i = 0; i < a.size(); ++i) a[i] = n++;
cout << a << '\n';
a.insert(3, 10);
cout << a << '\n';
a.insert(6, 20);
cout << a << '\n';
}