Vector in C++ is one of the most widely used containers from the Standard Template Library. A std::vector is a dynamic array, which means it stores elements in contiguous memory like an array, but unlike a fixed array, its size can grow and shrink automatically at runtime. This combination of flexible sizing and fast random access makes vector the default sequence container in many C++ programs.
This topic matters because vectors appear everywhere in modern C++ code. If you need to store a list of values whose size is not known at compile time, a vector is often the first and best choice. It works well with STL algorithms, supports range-based loops, offers strong cache-friendly performance, and avoids the manual memory management burden that comes with raw dynamic arrays. If you understand vectors well, you understand a large part of practical STL programming.
What Is Vector in C++?
A vector in C++ is a sequence container provided by the STL that stores elements in contiguous memory and can change size dynamically. Because the elements are stored contiguously, a vector supports fast index-based access just like a normal array. Because it can resize itself, it is much more flexible than a built-in array.
In simple terms, a vector is like an array that manages its own memory automatically. You can add elements, remove elements, iterate through them, and use standard algorithms with them without manually allocating and freeing memory yourself.
Vector in C++ is a dynamic array container from the STL that offers contiguous storage, automatic resizing, and fast random access.
Why Vector Is Needed in C++
Built-in arrays in C++ are useful, but they have limitations. Their size is fixed once created, and working with dynamic arrays manually often means handling raw pointers, allocation, deallocation, and copying concerns yourself. That quickly becomes error-prone.
- Vectors can grow when new elements are added.
- Vectors automatically manage dynamic memory.
- Vectors work directly with STL algorithms and iterators.
- Vectors provide convenient member functions for common operations.
- Vectors are often safer and easier to use than raw dynamic arrays.
This makes vectors one of the most practical containers for everyday programming tasks.
Header File and Syntax of Vector in C++
To use a vector, include the <vector> header and declare a vector with the desired element type.
#include <vector>
std::vector<int> numbers;
Here numbers is a vector that can store integers. At first it is empty, but elements can be added later.
How to Initialize a Vector in C++
Vectors can be initialized in several useful ways depending on what kind of starting state you want.
std::vector<int> a;
std::vector<int> b(5);
std::vector<int> c(5, 10);
std::vector<int> d = {1, 2, 3, 4, 5};
ais an empty vector.bcontains 5 default-initialized integers.ccontains 5 integers, each with value 10.dis initialized with a list of values.
These forms cover most common vector creation patterns in beginner and intermediate code.
Adding Elements to a Vector
The most common way to add elements to a vector is push_back(), which inserts an element at the end of the vector.
std::vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
After these operations, the vector contains three elements. If the current storage is not enough, the vector automatically allocates more memory and moves or copies existing elements as needed.
Accessing Elements in a Vector
Because vector elements are stored contiguously, they can be accessed by index just like an array.
std::vector<int> numbers = {10, 20, 30};
std::cout << numbers[0] << std::endl;
std::cout << numbers.at(1) << std::endl;
The [] operator gives direct access without bounds checking. The at() function performs bounds checking and is safer when you want runtime validation. Vectors also provide front() and back() for accessing the first and last elements.
Important Vector Functions in C++
Vectors provide many useful member functions for managing size, elements, and storage.
| Function | Purpose |
|---|---|
push_back() | Add element at the end |
pop_back() | Remove last element |
size() | Return number of elements |
empty() | Check whether the vector is empty |
clear() | Remove all elements |
insert() | Insert elements at a position |
erase() | Remove elements from a position or range |
front() | Access first element |
back() | Access last element |
resize() | Change the logical size |
Learning these functions gives you most of the basic control you need for everyday vector usage.
Iterating Through a Vector
Vectors can be traversed in several common ways. Each style is useful in different contexts.
std::vector<int> values = {1, 2, 3, 4};
for (size_t i = 0; i < values.size(); i++)
{
std::cout << values[i] << " ";
}
for (int x : values)
{
std::cout << x << " ";
}
for (std::vector<int>::iterator it = values.begin(); it != values.end(); ++it)
{
std::cout << *it << " ";
}
Index-based loops, range-based loops, and iterator-based loops are all valid. Range-based loops are especially clean when you only need to visit each element.
Size vs Capacity in Vector
One of the most important concepts in vectors is the difference between size() and capacity(). The size is the number of actual elements currently stored. The capacity is the amount of allocated storage available before the vector must reallocate.
std::vector<int> values;
values.push_back(10);
values.push_back(20);
std::cout << values.size() << std::endl;
std::cout << values.capacity() << std::endl;
Capacity is usually greater than or equal to size. Understanding this difference helps explain why vectors sometimes reallocate and why references or iterators may become invalid after growth operations.
Using reserve() with Vector
If you know approximately how many elements a vector will hold, reserve() can improve performance by allocating enough capacity in advance. This reduces the number of reallocations that may happen during repeated push_back() calls.
std::vector<int> values;
values.reserve(100);
This does not change the size of the vector. It changes the reserved storage capacity only.
Inserting and Erasing Elements in Vector
Vectors support insertion and removal at positions other than the end, but such operations can be more expensive because elements may need to shift.
std::vector<int> values = {1, 2, 4, 5};
values.insert(values.begin() + 2, 3);
values.erase(values.begin());
After insertion, the vector becomes {1, 2, 3, 4, 5}. After erasing the first element, it becomes {2, 3, 4, 5}. These operations are convenient, but for frequent middle insertions or deletions, another container such as list may sometimes be more suitable.
Vector vs Array in C++
Vectors and arrays both store elements in contiguous memory, but they differ in flexibility and convenience.
| Feature | Array | Vector |
|---|---|---|
| Size | Fixed | Dynamic |
| Memory management | Manual or fixed lifetime | Automatic |
| STL compatibility | Limited compared with vector interface | Excellent |
| Convenience functions | Very limited | Many built-in utilities |
Because of this, vectors are often preferred over raw dynamic arrays in modern C++ unless there is a very specific low-level reason to use raw storage.
Vector and STL Algorithms
Vectors work extremely well with STL algorithms because they provide random access iterators. This means many algorithms, including sort(), can operate efficiently on vectors.
#include <algorithm>
#include <vector>
std::vector<int> values = {4, 1, 7, 2};
std::sort(values.begin(), values.end());
This is one reason vectors are often the first container developers reach for. They cooperate well with the broader STL ecosystem.
When to Use Vector in C++
- Use vector when you need dynamic-size sequence storage.
- Use it when fast random access by index matters.
- Use it when you want strong compatibility with STL algorithms.
- Use it as the default sequence container unless another container fits the access pattern better.
That last point is important. In modern C++, vector is often the default sequence container, not the exception.
Common Mistakes with Vector in C++
- Confusing
size()withcapacity(). - Using
[]when bounds checking withat()is more appropriate. - Assuming iterators and references always remain valid after insertions or growth.
- Using vector for patterns where frequent middle insertions dominate performance.
- Calling
reserve()and expecting it to change the actual number of elements.
These are the kinds of mistakes that disappear once the internal behavior of vector is understood clearly.
push_back() vs emplace_back() in Vector
Besides push_back(), vectors also provide emplace_back(). The difference is that push_back() adds an existing object to the end, while emplace_back() constructs the element directly in place at the end of the vector. This can be especially useful for complex user-defined objects because it may avoid an extra temporary object.
Iterator and Reference Invalidation in Vector
When a vector grows and reallocates its internal storage, existing pointers, references, and iterators to its elements can become invalid. This is a very important practical rule. If code stores an iterator to a vector element and then the vector expands, that stored iterator may no longer be safe to use. Understanding this behavior helps prevent subtle bugs in larger STL-based programs.
Vector of Objects in C++
Vectors are not limited to primitive types. They can store objects of user-defined classes as well, which makes them extremely useful in real applications. A vector of objects is common in menu systems, simulations, embedded host tools, inventory lists, and many business-style applications where structured records must be stored dynamically.
Best Practices for Vector in C++
- Prefer vector over raw dynamic arrays in normal modern C++ code.
- Use
reserve()when expected growth is known. - Use range-based loops for simple traversal and iterators when algorithm interfaces need them.
- Choose
at()when safety matters more than minimal overhead. - Use STL algorithms with vectors instead of rewriting common loops manually.
These habits make vector-based code safer, clearer, and more aligned with standard modern C++ style.
Important Rules to Remember About Vector in C++
- Vector is a dynamic array container in the STL.
- It stores elements in contiguous memory and supports fast random access.
- Its size can change automatically at runtime.
- It works very well with STL algorithms and iterators.
- It is often the default sequence container in modern C++ programming.
Continue learning C++ in order
Follow the topic sequence with the previous and next lesson.