Notes
๐ Complete Notes on Arrays, Dynamic Arrays, and STL Vectors in C++
๐ Table of Contents
-
Introduction
-
What is an Array?
-
When to Use Arrays (with Example)
-
Problems with Arrays
-
What is a Dynamic Array?
-
Dynamic Arrays vs. Arrays
-
What is a Vector (STL)?
-
Why Use Vectors Instead of Arrays?
-
Vector Syntax and Initialization
-
Common Vector Operations
-
Vector Iterators
-
Const Iterators
-
Useful Vector Methods
-
Inserting and Removing Elements
-
Vectors vs. Dynamic Arrays
-
Conclusion and Recommendations
๐ฐ 1. Introduction
In C++, managing collections of data efficiently is crucial. This guide explores three ways to handle collections of data:
-
Arrays
-
Dynamic Arrays
-
STL Vectors
Youโll learn the differences, advantages, and best use cases for each, focusing especially on STL Vectors, which are widely used due to their simplicity and power.
๐ฆ 2. What is an Array?
An array is a fixed-size collection of elements stored in contiguous memory locations.
Characteristics:
-
Elements are stored one after another in memory. It stores elements in subsequent memory locations (contiguous memory).
-
Fixed size: Once defined, its size cannot change.
-
Direct access using the index.
-
It holds elements that have the same data type.
int arr[10]; // Declares an array of size 10โ 3. When to Use Arrays (Example)
- Elements can be accessed easily and quickly, because they are available directly by using the name of the array and index of the element
Example: Top 100 Cryptocurrencies App
You are building an app that always shows the top 100 cryptocurrencies.
Why array is good here?
-
You always have exactly 100 elements.
-
Fast direct access using indexes.
-
No need for resizing.
Crypto top100[100];
top100[0] = {"Bitcoin", 65000};โ ๏ธ 4. Problems with Arrays
Arrays can lead to issues if:
-
The size of the array is allocated at compile-time, and it must be specified in the declaration.
-
That means that its size must be a constant expression and cannot be changed while the program is running.
-
The size requirement changes dynamically.
-
You hard-code the size, but:
-
More data arrives than expected (overflow).
-
Less data than expected (waste of memory).
-
Example:
You expect 100 students in a course, but:
-
1,000 apply โ Cannot add more.
-
Only 10 enroll โ Wasted memory (the array still reserves space for 100).
๐ 5. What is a Dynamic Array?
A Dynamic Array can resize itself at runtime.
- A dynamic array is Like a standard array, with one key difference : > Its size is not constant and can be changed while the program is running.
How it works:
-
Initially allocates memory for some size.
-
If more elements are added:
-
Allocates new larger array.
-
Copies old elements.
-
Deletes the old array.
-
-
Automatically shrinks if elements are removed.
Benefit:
-
With the help of dynamic arrays, you wonโt have to waste memory because you can adjust the size of the array to the number of elements that it contains (increase its size when new elements are added and decrease its size when elements are removed)
-
Memory is used more efficiently.
-
Can grow or shrink based on data.
Limitations:
- Every time you want to increase/decrease the size of the array, in the background that process looks like this:
- allocate the space for a bigger/smaller array
- copy all the elements from the old array to the new array
- delete the old array This optimizes the use of memory, but it requires additional execution time.
int* arr = new int[initialSize]; // You manage size and memory๐ 6. Dynamic Arrays vs Arrays
| Feature | Array | Dynamic Array |
|---|---|---|
| Fixed Size | Yes | No |
| Manual Resize | Not Possible | Yes, using new/delete |
| Memory Usage | May waste memory | Efficient (adaptive) |
| Syntax | Simple | Complex (requires memory management) |
๐ 7. What is a Vector?
A Vector is a dynamic array from the STL (Standard Template Library) that automatically handles memory for you.
Properties:
-
- Vector provides you with all the benefits of the dynamic array, with less work and errors.
-
Stores elements contiguously like arrays (unlike some other collections, e.g. linked list).
-
Automatically resizes as needed i.e. when an element is inserted or deleted .
-
Provides many built-in methods for manipulation.
#include <vector>
std::vector<int> numbers;๐ค 8. Why Use Vectors?
-
Easy to use.
-
No need to manage memory manually.
-
Safe (STL vectors are tested and widely used).
-
Cleaner, more readable code.
๐งฐ 9. Vector Syntax and Initialization
#include <vector>
std::vector<int> numbers; // Create an empty vector
// Add elements using push_back
numbers.push_back(1);
numbers.push_back(2);
// Create a vector with size and default value
std::vector<int> values(5, 10); // {10, 10, 10, 10, 10}๐ 10. Common Vector Operations
// Add elements
numbers.push_back(5);
// Access elements
int first = numbers[0]; // Using []
int second = numbers.at(1); // Using at()
// Modify elements
numbers[0] = 100;
// Remove last element
numbers.pop_back();
// Resize the vector
numbers.resize(3);
// Check size and capacity
numbers.size(); // Current number of elements
numbers.capacity(); // Memory allocated before resize
numbers.max_size(); // Max elements allowed
// Clear all elements
numbers.clear();๐ 11. Vector Iterators
Iterators are like pointers that help traverse vectors.
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << std::endl;
}You can:
-
*it: Access value -
&(*it): Address of value -
&it: Address of the iterator (rare)
๐ก๏ธ 12. Const Iterators (cbegin, cend)
cbegin() and cend() return constant iterators.
-
You cannot modify the vector through these.
-
Used when you only want to read values.
for (auto it = numbers.cbegin(); it != numbers.cend(); ++it) {
std::cout << *it << std::endl; // OK
// *it = 5; // โ ERROR! Read-only
}๐งฎ 13. Useful Vector Methods
| Function | Description |
|---|---|
size() | Current size |
capacity() | Max elements before resize needed |
resize(n) | Resize vector to n elements |
empty() | Checks if vector is empty |
clear() | Removes all elements |
front() | Returns first element |
back() | Returns last element |
insert(pos, val) | Inserts val at given position |
erase(pos) | Removes element at given position |
pop_back() | Removes last element |
at(i) | Safer way to access index (with bounds checking) |
๐ ๏ธ 14. Inserting and Removing Elements
Insert:
numbers.insert(numbers.begin() + 2, 88); // Insert at index 2Erase:
numbers.erase(numbers.begin() + 2); // Remove element at index 2Pop Back:
numbers.pop_back(); // Removes last elementโ๏ธ 15. Vectors vs Dynamic Arrays
| Feature | Vector (STL) | Dynamic Array (Manual) |
|---|---|---|
| Memory Management | Automatic | Manual (use new/delete) |
| Built-in Methods | Rich set of tools (push_back, etc) | None |
| Performance | Slightly less optimal in rare cases | Can be faster (rarely) |
| Safety | Safer, less prone to bugs | More error-prone |
| Use Case | Everyday development | Rare performance-critical cases |
- VECTOR VS STATIC ARRAY
- Vector is better if you are going to change the size of your collection and insert/delete elements frequently.
- Static array is much better if the size of your collection will not change but you want to access the elements frequently.
| Vector | Dynamic Array |
|---|---|
| Vector hides memory management from the programmer, and it provides a programmer with a lot of useful functionalities that you can use in order to work with Vector collection. | With dynamic arrays, you can manage memory yourself, and get slight performance improvements, but you risk making a lot of bugs in that process. |
| It is tested, not error-prone, and standardized and millions of developers know how to use it. |
โ
Recommendation: Use vectors 99% of the time.
โ Use dynamic arrays only if:
-
You hit a performance bottleneck.
-
You know exactly what youโre doing.
-
Youโve profiled both solutions.
๐ 16. Conclusion
-
Arrays are good when the size is fixed and known.
-
Dynamic arrays offer resizing, but require manual memory management.
-
Vectors are the best tool for dynamic, resizable collections in C++.
-
STL Vectors are:
-
Safe
-
Efficient
-
Easy to use
-
Feature-rich
-
๐ง Pro Tip: Vectors are a thin wrapper over dynamic arrays, meaning they are nearly as fast, but far more convenient.
๐ Bonus: When to Use What?
| Scenario | Use |
|---|---|
| Fixed size, fast access, memory-critical | Array |
| Size changes at runtime, low-level memory control | Dynamic Array |
| General-purpose resizable data storage | Vector โ |