gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
write a function for dynamic array in C++ on void increaseArraySize()
- User
write a function for dynamic array in C++ on void increaseArraySize()
- Assistant
Here's a sample implementation of a dynamic array in C++ and a function to increase its size dynamically:
#include <iostream> class DynamicArray { int *arr; // Pointer to dynamic array int capacity; // Current capacity of the array int size; // Current number of elements in the array public: // Constructor DynamicArray() { arr = new int[1]; // Initialize with initial capacity of 1 capacity = 1; size = 0; } // Function to increase the size of the array dynamically void increaseArraySize() { // Double the capacity capacity *= 2; int *tempArr = new int[capacity]; // Create a new array with the increased capacity // Copy elements from the old array to the new array for (int i = 0; i < size; i++) { tempArr[i] = arr[i]; } delete[] arr; // Deallocate memory of old array arr = tempArr; // Update array pointer to the new array std::cout << "Array size increased to " << capacity << std::endl; } // Function to add an element to the array void addElement(int element) { // Check if the array is full if (size == capacity) { increaseArraySize(); // Increase the array size if full } // Add the element to the array arr[size] = element; size++; } }; int main() { DynamicArray dynArr; // Add elements to the array dynArr.addElement(10); dynArr.addElement(20); dynArr.addElement(30); return 0; }