Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- // Пишем класс векторов
- template <typename T>
- class Vector {
- T* array;
- int size;
- int capacity;
- public:
- // Конструктор инициилизации
- Vector(){
- array = nullptr;
- size = 0;
- capacity = 0;
- }
- // Конструктор копирования
- Vector(const Vector& other){
- size = other.size;
- capacity = other.capacity;
- array = new T[capacity];
- for (int i = 0; i < size; ++i){
- array[i] = other.array[i];
- }
- }
- // Перегружаем равно
- Vector& operator=(const Vector& other){
- if (this != &other){
- delete[] array;
- size = other.size;
- capacity = other.capacity;
- array = new T[capacity];
- for (int i=0; i < size; ++i){
- array[i] = other.array[i];
- }
- }
- return *this;
- }
- // Доступы:
- T& operator[](int index){
- return array[index];
- }
- const T& operator[](int index) const{
- return array[index];
- }
- int getSize() const{
- return size;
- }
- int getCapacity() const{
- return capacity;
- }
- // Push и Pop
- void push_back(const T& value){
- if (size == capacity){
- if (capacity == 0){
- reserve(1);
- } else {
- reserve (capacity * 2);
- }
- }
- array[size] = value;
- ++size;
- }
- void pop_back(){
- if (size > 0){
- --size;
- }
- }
- // Резервация - задаем новую вместимость
- void reserve(int new_capacity){
- if (new_capacity > capacity){
- T* new_array = new T[new_capacity];
- for (int i = 0; i < size; ++i){
- new_array[i] = array[i];
- }
- delete[] array;
- array = new_array;
- capacity = new_capacity;
- }
- }
- // Ресайз - добавляем значение
- void resize(int new_size, const T& value){
- if (new_size > capacity){
- reserve(new_size);
- }
- for (int i = size; i < new_size; ++i){
- array[i] = value;
- }
- size = new_size;
- }
- // Деструктор
- ~Vector(){
- delete[] array;
- }
- };
- int main() {
- Vector<int> vec;
- vec.push_back(1);
- vec.push_back(2);
- vec.push_back(3);
- cout << "Размер: " << vec.getSize() << endl;
- cout << "Объем: " << vec.getCapacity() << endl;
- cout << "Элемент по индексу 0: " << vec[0] << endl;
- cout << "Элемент по индексу 1: " << vec[1] << endl;
- cout << "Элемент по индексу 0: " << vec[2] << endl;
- vec.pop_back();
- cout << "Размер после pop_back: " << vec.getSize() << endl;
- vec.resize(5, 10);
- cout << "Размер после ресайза: " << vec.getSize() << endl;
- cout << "Элемент по индексу 3: " << vec[3] << endl;
- cout << "Элемент по индексу 3: " << vec[4] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement