Notes

๐Ÿ“š Complete Notes on Arrays, Dynamic Arrays, and STL Vectors in C++


๐Ÿ“Œ Table of Contents

  1. Introduction

  2. What is an Array?

  3. When to Use Arrays (with Example)

  4. Problems with Arrays

  5. What is a Dynamic Array?

  6. Dynamic Arrays vs. Arrays

  7. What is a Vector (STL)?

  8. Why Use Vectors Instead of Arrays?

  9. Vector Syntax and Initialization

  10. Common Vector Operations

  11. Vector Iterators

  12. Const Iterators

  13. Useful Vector Methods

  14. Inserting and Removing Elements

  15. Vectors vs. Dynamic Arrays

  16. 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:

  1. Initially allocates memory for some size.

  2. If more elements are added:

    • Allocates new larger array.

    • Copies old elements.

    • Deletes the old array.

  3. 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:
    1. allocate the space for a bigger/smaller array
    2. copy all the elements from the old array to the new array
    3. 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

FeatureArrayDynamic Array
Fixed SizeYesNo
Manual ResizeNot PossibleYes, using new/delete
Memory UsageMay waste memoryEfficient (adaptive)
SyntaxSimpleComplex (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

FunctionDescription
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 2

Erase:

numbers.erase(numbers.begin() + 2); // Remove element at index 2

Pop Back:

numbers.pop_back(); // Removes last element

โš”๏ธ 15. Vectors vs Dynamic Arrays

FeatureVector (STL)Dynamic Array (Manual)
Memory ManagementAutomaticManual (use new/delete)
Built-in MethodsRich set of tools (push_back, etc)None
PerformanceSlightly less optimal in rare casesCan be faster (rarely)
SafetySafer, less prone to bugsMore error-prone
Use CaseEveryday developmentRare 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.
VectorDynamic 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?

ScenarioUse
Fixed size, fast access, memory-criticalArray
Size changes at runtime, low-level memory controlDynamic Array
General-purpose resizable data storageVector โœ…

References