Dynamic Array in C++ With Examples

Dec 28, 2023

4 mins read

Published in
C++

The Dynamic Array in c++ with examples

Our DynamicArray class manages an array that may dynamically develop in size. The class has a pointer array to shop the factors, length to preserve song of the variety of elements, and capacity to represent the array’s cutting-edge potential.

Dynamic Memory Allocation:

When pushing an detail the use of pushBack(), the magnificence exams if the array is full. If so, it doubles its capacity and creates a new array with the accelerated length. This ensures efficient reminiscence usage and decreases the need for common resizing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

class DynamicArray {
private:
    int* arr;
    int size;
    int capacity;

public:
    DynamicArray() : size(0),  capacity(2) {
        arr = new int[capacity];
    }

    ~DynamicArray() {
        delete[] arr;
    }

    void push_back(int element) {
        if (size == capacity) {
            int* newArr = new int[capacity * 2];
            for (int i = 0; i < size; ++i) {
                newArr[i] = arr[i];
            }
            delete[] arr;
            arr = newArr;
            capacity *= 2;
        }
        arr[size++] = element;
    }

    int at(int index) const {
        if (index < 0 || index >= size) {
            throw std::out_of_range("Index out of bounds");
        }
        return arr[index];
    }

    int getSize() const {
        return size;
    }

    int getCapacity() const {
        return capacity;
    }
};

int main() {
    DynamicArray dynArray;

    for (int i = 1; i <= 10; ++i) {
        dynArray. push_back(i * 10);
    }

    std::cout << "Dynamic Array Size: " << dynArray. getSize() << std::endl;
    std::cout << "Dynamic Array Capacity: " << dynArray. getCapacity() << std::endl;

    for (int i = 0; i < dynArray. getSize(); ++i) {
        std::cout << "Element at index " << i << ": " << dynArray. at(i) << std::endl;
    }

    return 0;
}

Explanation

In C++, a dynamic array is implemented using pointers and memory allocation. Unlike a static array, a dynamic array allows resizing during runtime, making it more flexible when the size of the data set is unknown or may change.

  1. The DynamicArray class in the example starts by declaring a private integer pointer arr, which points to the dynamically allocated array. It also includes size to keep track of the current number of elements in the array and capacity to denote the total allocated memory size.

  2. The constructor initializes the dynamic array with an initial capacity of 2. This initial capacity can be adjusted based on the specific requirements of your program. The destructor ensures that the allocated memory is freed when the object goes out of scope.

  3. The push_back method is used to add elements to the dynamic array. If the current size of the array equals its capacity, it means the allocated memory is full, and the array needs to be resized. The method then creates a new array with twice the capacity, copies the existing elements into the new array, deletes the old array, and updates the pointer to the new array.

  4. The at method is a getter that returns the element at a specified index. It includes boundary checking to prevent accessing elements outside the valid range of the array.

  5. The getSize and getCapacity methods are simple accessor functions to retrieve the current size and capacity of the dynamic array, respectively.

  6. In the main function, an instance of DynamicArray is created, and elements are added using the push_back method in a loop. This demonstrates the dynamic nature of the array, which can grow as needed.

Finally, the size, capacity, and elements of the dynamic array are printed to the console for verification.

Sharing is caring!