Dynamic Data Structures in C++


Dynamic data structures in C++ are essential for managing and organizing data that can change in size during program execution. In this guide, we'll explore dynamic data structures, including arrays, linked lists, and vectors, with sample code and explanations.


1. Arrays

Arrays are collections of elements of the same data type. In C++, you can create dynamic arrays using pointers or use the standard library's std::vector for a more versatile dynamic array:


#include <iostream>
#include <vector>
int main() {
// Using a dynamic array (vector)
std::vector<int> dynamicArray;
dynamicArray.push_back(1);
dynamicArray.push_back(2);
dynamicArray.push_back(3);
std::cout << "Dynamic Array Elements:" << std::endl;
for (int element : dynamicArray) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}

2. Linked Lists

Linked lists are dynamic data structures where each element (node) points to the next one. Linked lists come in various forms, including singly linked lists and doubly linked lists. Here's a sample of a singly linked list:


#include <iostream>
struct Node {
int data;
Node* next;
};
int main() {
// Create a linked list
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
// Traverse the linked list
Node* current = head;
std::cout << "Linked List Elements:" << std::endl;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
return 0;
}

3. Dynamic Data Structures

Dynamic data structures adapt to changing data sizes. The C++ standard library provides several dynamic data structures, including std::vector, std::list, and std::map. Here's an example of using a dynamic array (vector):


#include <iostream>
#include <vector>
int main() {
// Using a dynamic array (vector)
std::vector<int> dynamicArray;
dynamicArray.push_back(1);
dynamicArray.push_back(2);
dynamicArray.push_back(3);
std::cout << "Dynamic Array Elements:" << std::endl;
for (int element : dynamicArray) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}

4. Memory Management

Proper memory management is crucial when using dynamic data structures. In C++, you need to deallocate memory explicitly to prevent memory leaks. For dynamic arrays, use delete, and for linked lists, release memory using delete for each node:


// Deallocate memory for a dynamic array
delete[] dynamicArray;
// Deallocate memory for a linked list
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}

Conclusion

Dynamic data structures in C++ are essential for managing data that can change in size. By understanding arrays, linked lists, and dynamic data structures provided by the C++ standard library, you can create flexible and efficient data structures to handle changing data needs in your C++ programs.