C++ data structures
Created By: chatGPT
Data structures in C++ are essential for organizing and managing data efficiently. They allow programmers to handle data in a way that's both manageable and effective. The most commonly used data structures in C++ include arrays, linked lists, stacks, queues, trees, and graphs.
Arrays are collections of elements identified by index. They are fixed in size, which can lead to inefficiencies if you need to resize often.
int arr[10]; // Declaration of an array of size 10
Linked lists consist of nodes where each node contains data and a reference to the next node. This structure is dynamic and allows for efficient insertions and deletions.
struct Node {
int data;
Node* next;
};
Node* head = nullptr; // Initialize an empty list
Stacks are LIFO (Last In, First Out) structures. You can only add or remove elements from the top of the stack. They are commonly used in programming for managing function calls and backtracking algorithms.
std::stack<int> s;
s.push(10); // Add to stack
s.pop(); // Remove from stack
Queues are FIFO (First In, First Out) structures. In a queue, elements are added at the back and removed from the front. They are useful for managing tasks that need processing in order.
std::queue<int> q;
q.push(10); // Add to queue
q.pop(); // Remove from queue
Trees are hierarchical structures that consist of nodes, where each node contains a value and references to child nodes. Binary trees are a specific type of tree with two children per node. Trees can be used to represent sorted data for efficient searching.
struct TreeNode {
int value;
TreeNode* left;
TreeNode* right;
};
Graphs are collections of nodes (vertices) connected by edges. They can be used for representing networks such as social connections, transportation grids, etc. Graphs can either be directed or undirected.
class Graph {
private:
std::unordered_map<int, std::vector<int>> adjList;
public:
void addEdge(int u, int v) {
adjList[u].push_back(v);
}
};