Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- class Vector {
- public:
- Vector() : arr_(new int[4]), size_(0), capacity_(4) {}
- Vector(const int new_capacity) : arr_(new int[new_capacity]), size_(0), capacity_(new_capacity) {}
- void push_back(const int value) {
- check_capacity_();
- arr_[size_] = value;
- size_++;
- total_number_elements_++;
- }
- void insert(const int index, const int value) {
- if (index < 0 || index >= size_) {
- cout << "Invalid index" << endl;
- return;
- }
- check_capacity_();
- for (int i = size_; i > index; i--) {
- arr_[i] = arr_[i - 1];
- }
- arr_[index] = value;
- size_++;
- }
- void erase(const int index) {
- if (index < 0 || index >= size_) {
- cout << "Invalid index" << endl;
- return;
- }
- for (int i = index; i < size_ - 1; i++) {
- arr_[i] = arr_[i + 1];
- }
- size_--;
- }
- int get_value(const int index) {
- if (index >=0 && index < size_) {
- return arr_[index];
- }
- }
- void set_value(const int index, const int value) {
- if (index < 0 || index >= size_) {
- cout << "Invalid index" << endl;
- return;
- }
- arr_[index] = value;
- }
- void pop_back() {
- size_--;
- }
- void print() {
- for (int i = 0; i < size_; i++) {
- cout << arr_[i] << " ";
- }
- cout << endl;
- }
- int size() {
- return size_;
- }
- int capacity() {
- return capacity_;
- }
- ~Vector() {
- delete[] arr_;
- }
- static int get_total_number_elements() {
- return total_number_elements_;
- }
- private:
- int* arr_; // массив для хранения элементов
- int size_; // текущее количество элементов в массиве
- int capacity_; // вместимость (емкость) массива
- static int total_number_elements_; // общее количество элементов всех экземпляров класса Vector
- void check_capacity_() {
- if (size_ == capacity_) {
- int* temp = new int[capacity_ * 2];
- for (int i = 0; i < size_; i++) {
- temp[i] = arr_[i];
- }
- delete[] arr_;
- arr_ = temp;
- capacity_ *= 2;
- }
- }
- };
- void Print(vector<int>& vec) {
- for (int a : vec) {
- cout << a << " ";
- }
- cout << endl;
- }
- int Vector::total_number_elements_ = 0;
- int main() {
- setlocale(LC_ALL, "ru");
- Vector vec2;
- vec2.print();
- vec2.push_back(35);
- vec2.print();
- for (int i = 0; i < 10; i++) {
- vec2.push_back(i + 1);
- }
- vec2.print();
- vec2.pop_back();
- vec2.print();
- vec2.insert(2, 55);
- vec2.print();
- vec2.erase(3);
- vec2.print();
- cout << vec2.get_value(3) << endl;
- vec2.set_value(3, 33);
- vec2.print();
- cout << "Элементов в векторе: " << vec2.size() << " Емкость вектора: " << vec2.capacity() << endl;
- Vector vec3(100);
- cout << "Элементов в векторе: " << vec3.size() << " Емкость вектора: " << vec3.capacity() << endl;
- cout << Vector::get_total_number_elements() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment