Vector in Computer Science: Definition, Uses & Examples
In this article
A vector in computer science is a dynamic array—a contiguous block of memory that can grow or shrink as elements are added or removed.
Origin of the Term “Vector”
The word vector comes from the Latin vehere, meaning “to carry.” In mathematics it describes a quantity that has both magnitude and direction, and it was first formalised in the 19th‑century work on analytic geometry. Early computer scientists borrowed the term because a dynamic array “carries” a sequence of items in memory, much like a mathematical vector carries a list of components. The first widely recognised use in programming appeared in the 1970s with the implementation of the vector class in the C++ Standard Template Library (STL). In everyday speech a programmer might say, “I stored the sensor readings in a vector for fast random access.”
Mathematical vs. Programming Vectors
Although the names are identical, the two concepts serve different purposes:
- Mathematical vector: a fixed‑size tuple of numbers (e.g., (3, 5, ‑2)) used in linear algebra, physics, and graphics.
- Programming vector: a resizable container that holds elements of any type, providing O(1) amortised time for appending and O(1) random access.
Confusing the two can lead to bugs. For instance, in C++ the std::vector<double> type is a container, not a geometric vector; geometric operations are performed by libraries such as Eigen or GLM, which define their own Vector classes.
How Vectors Work Internally
Under the hood a vector maintains three pieces of state:
- Pointer to the start of the allocated block. This is the address of the first element.
- Current size (number of constructed elements). The size grows when
push_backoremplace_backis called. - Capacity (size of the allocated block). Capacity is usually larger than size; when size reaches capacity the vector allocates a new block, copies or moves existing elements, and frees the old block.
The reallocation strategy is implementation‑defined but most libraries double the capacity each time it is exceeded. Doubling guarantees amortised O(1) insertion at the end while keeping the number of allocations logarithmic in the final size.
Common Operations and Their Complexity
Understanding the cost of each operation helps you decide when a vector is the right tool.
| Operation | Complexity (worst case) | Typical Use |
|---|---|---|
Access by index (operator[], at()) | O(1) | Random reads or writes. |
Push back (push_back) | Amortised O(1), worst‑case O(n) when reallocation occurs | Building a list of items when the final size is unknown. |
| Insert at arbitrary position | O(n) | Rarely needed; use list if frequent mid‑sequence inserts are required. |
| Erase at arbitrary position | O(n) | Same caveat as insert. |
| Iterate (forward or reverse) | O(n) | Processing all elements. |
| Resize to smaller size | O(1) (destructors may run) | Truncating a collection. |
Choosing a Vector Over Other Containers
When deciding between a vector and alternatives such as linked lists, deques, or hash tables, ask yourself three questions:
- Do I need fast random access? If yes, a vector is usually the best choice.
- Will I mostly add or remove elements at the end? Vectors excel at tail operations.
- Is memory locality important? Because elements are stored contiguously, vectors benefit from CPU cache prefetching.
If the answer to any of these is “no,” consider another container. For example, a std::list provides O(1) insertion anywhere but suffers from poor cache performance, while a std::deque offers O(1) insertion at both ends but uses a segmented memory layout.
Common Pitfalls and How to Avoid Them
Even experienced developers stumble over a few classic vector mistakes:
- Invalidating iterators after reallocation. When a vector grows, all pointers, references, and iterators become dangling. Always obtain a fresh iterator after a
push_backthat might trigger a resize. - Assuming
operator[]checks bounds. It does not; useat()if you need a runtime exception on out‑of‑range access. - Excessive copying. Passing a vector by value copies the entire container. Prefer
const ¶meters or move semantics (e.g.,std::move) when ownership transfer is intended. - Using the deprecated Java
Vectorclass. Java’sVectoris synchronized and slower thanArrayList. ChooseArrayListunless you need thread‑safe operations.
To guard against these issues, follow a simple checklist before mutating a vector:
- Reserve expected capacity with
reserve()to minimise reallocations. - Prefer range‑based for loops or iterators obtained after any mutation.
- Use
emplace_back()when constructing objects in place to avoid extra copies.
Comparisons with Similar Data Structures
Below is a quick side‑by‑side comparison of vectors with three frequently confused structures.
| Structure | Random Access | Insertion at End | Insertion in Middle | Memory Overhead |
|---|---|---|---|---|
| Vector (dynamic array) | O(1) | Amortised O(1) | O(n) | Low (single contiguous block) |
| Linked List | O(n) | O(1) if tail pointer kept | O(1) once position located | High (node pointers per element) |
| Deque | O(1) but not contiguous | O(1) | O(n) | Moderate (multiple blocks) |
For most algorithmic work where the data size is known or grows predictably, the vector provides the best trade‑off between speed and memory use.
Frequently Asked Questions
Is a vector the same as an array?
No. An array has a fixed size determined at compile time (in C/C++) or at creation (in languages like Java). A vector can resize itself at runtime, handling memory allocation automatically.
Can I store objects of different types in a single vector?
Not directly. A vector is a homogeneous container; all elements must share the same type. To store heterogeneous data you can use a vector of std::variant, pointers to a common base class, or a language‑specific “any” type.
What does the reserve() function do?
reserve(n) pre‑allocates memory for at least n elements, preventing reallocations until the size exceeds that capacity. This improves performance when you know the final size in advance.
Why does Java have both Vector and ArrayList?
Java’s Vector predates the collections framework and is synchronized, making it thread‑safe but slower. ArrayList was introduced later as the unsynchronized, faster alternative for single‑threaded code.
Is a C++ std::vector<bool> a true vector?
Specialisation of std::vector<bool> packs bits together to save space, which means it does not provide true references to individual elements. For bit‑level manipulation, use std::bitset or a dedicated bitmap library.