🛠️ C++ Tools & Ecosystem
Estimated reading: 3 minutes 271 views

C++ <vector> – Dynamic Arrays with std::vector Explained


Introduction – Why Use <vector> in C++

C++ provides dynamic and resizable arrays using the std::vector class from the <vector> header. Unlike static arrays, vectors can grow or shrink in size at runtime, support random access, and integrate seamlessly with STL algorithms and iterators.

In this guide, you’ll learn:

  • How to declare and initialize vectors
  • Key operations: push_back(), insert(), erase(), resize()
  • How vectors compare to arrays and lists
  • Performance tips and common use cases

What Is <vector> in C++?

The <vector> header provides the std::vector class—a sequence container representing a dynamic array. It stores elements contiguously in memory, offering fast element access by index and efficient memory management.

Include it with:

#include <vector>

Declare a vector:

std::vector<int> numbers;

Code Examples – With Output

Declare and Add Elements

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);

    for (int x : v)
        cout << x << " ";
    return 0;
}

Output:

10 20 30

Initialize a Vector

vector<int> v1 = {1, 2, 3};
vector<int> v2(5, 100); // 5 elements, all 100

Common std::vector Methods

MethodDescription
push_back(val)Adds element to end
pop_back()Removes last element
insert(pos, val)Inserts value at position
erase(pos)Removes element at position
clear()Removes all elements
size()Returns number of elements
resize(n)Resizes vector to n elements
front() / back()First and last elements
at(index)Access with bounds checking
[]Access without bounds checking
empty()Returns true if vector is empty

Traversing Vectors

Using Iterators

for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << " ";

Range-Based Loop (C++11+)

for (int x : v)
    cout << x << " ";

Vector vs Array vs List

Featurevectorarraylist
Size flexibility Dynamic Static Dynamic
Random access Yes Yes No
Insert/remove middle Slow N/A Fast
Memory layout Contiguous Contiguous Non-contiguous

Best Practices & Tips

Use .reserve(n) to avoid reallocations when size is known
Prefer emplace_back() over push_back() for efficiency with objects
Don’t use [] for unchecked access—prefer .at() for safety
Use shrink_to_fit() to reduce capacity after large deletions (non-binding)


Use Cases for Vectors

Dynamic Lists – Add/remove items at runtime
Matrix Representations – Use nested vector<vector<T>>
Stacks/Heaps – Can act as underlying storage
Game Engines – Store objects/entities with fast access
File Parsing – Store lines, tokens, or records


Summary – Recap & Next Steps

Key Takeaways:

  • std::vector is a dynamic array with random access and flexible resizing
  • Provides rich methods to add, remove, access, and modify data
  • Works with STL algorithms and supports iterators

Real-World Relevance:
Vectors are used everywhere—from embedded systems and financial tools to game engines and simulators—due to their simplicity and efficiency.

Next Steps:
Explore ⏰ C++ <ctime> to work with timestamps, clocks, and formatted time outputs.


FAQ – C++ <vector>

Is vector faster than list?
For random access and end insertions—yes. But for frequent insertions/removals in the middle, use list.

Can I access vector elements with indexing?
Yes. Use v[i] or v.at(i) for bounds checking.

Does vector automatically manage memory?
Yes. It grows dynamically and manages memory internally.

What’s the difference between reserve() and resize()?
reserve() allocates memory without changing size; resize() changes the number of accessible elements.

Can I use std::vector with STL algorithms?
Absolutely. Vectors are fully compatible with algorithms like sort(), find(), and accumulate().


Share Now :
Share

C++ <vector>

Or Copy Link

CONTENTS
Scroll to Top