#include <iostream>
#include <memory>
#include <algorithm>
#include <stdexcept>
#include <utility>
template<typename T>
class MyVector {
private:
T* data_;
size_t size_;
size_t capacity_;
void grow() {
size_t new_cap = capacity_ == 0 ? 1 : capacity_ * 2;
T* new_data = new T[new_cap];
for (size_t i = 0; i < size_; i++) {
new_data[i] = std::move(data_[i]);
}
delete[] data_;
data_ = new_data;
capacity_ = new_cap;
}
public:
MyVector() : data_(nullptr), size_(0), capacity_(0) {}
explicit MyVector(size_t count)
: data_(new T[count]), size_(count), capacity_(count) {}
~MyVector() {
delete[] data_;
}
MyVector(const MyVector&) = delete;
MyVector& operator=(const MyVector&) = delete;
MyVector(MyVector&& other) noexcept
: data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
other.data_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
}
MyVector& operator=(MyVector&& other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
size_ = other.size_;
capacity_ = other.capacity_;
other.data_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
}
return *this;
}
T& operator[](size_t index) {
return data_[index];
}
const T& operator[](size_t index) const {
return data_[index];
}
T& at(size_t index) {
if (index >= size_) throw std::out_of_range("Index out of range");
return data_[index];
}
size_t size() const { return size_; }
size_t capacity() const { return capacity_; }
bool empty() const { return size_ == 0; }
void push_back(T&& value) {
if (size_ >= capacity_) grow();
data_[size_++] = std::move(value);
}
void push_back(const T& value) {
if (size_ >= capacity_) grow();
data_[size_++] = value;
}
template<typename... Args>
T& emplace_back(Args&&... args) {
if (size_ >= capacity_) grow();
new (&data_[size_]) T(std::forward<Args>(args)...);
return data_[size_++];
}
void pop_back() {
if (size_ > 0) {
data_[--size_].~T();
}
}
T* begin() { return data_; }
T* end() { return data_ + size_; }
const T* begin() const { return data_; }
const T* end() const { return data_ + size_; }
};
int main() {
MyVector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::cout << "Elements: ";
for (auto& x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
struct Point { int x, y; };
MyVector<Point> points;
points.emplace_back(10, 20);
points.emplace_back(30, 40);
std::cout << "Point: (" << points[0].x << ", " << points[0].y << ")" << std::endl;
MyVector<int> v2 = std::move(v);
std::cout << "v2 size: " << v2.size() << std::endl;
std::cout << "v size: " << v.size() << " (moved)" << std::endl;
return 0;
}