What Data Structure Is Std::vector?


Larry Thompson

What is std::vector?

std::vector is a C++ template class that represents a dynamic array. It is part of the Standard Template Library (STL) that comes with the C++ Standard Library. The std::vector class provides a convenient way to store and manipulate collections of elements.

Features of std::vector:

  • Dynamic Size: Unlike traditional arrays, std::vector can dynamically resize itself to accommodate a varying number of elements.
  • Rapid Element Access: Elements in std::vector are stored in contiguous memory, allowing for constant-time random access using indices.
  • Add and Remove Elements: Elements can be added or removed from the end of the vector efficiently.
  • C++ Standard Library Compatibility: Being part of the C++ Standard Library, std::vector seamlessly integrates with other library components.

The underlying data structure:

The underlying data structure used by std::vector, as stated in the C++11 standard, is typically an array. The elements are stored contiguously in memory, allowing for efficient random access and iteration using pointers or iterators.

The array used by std::vector, however, may not always be contiguous if certain operations such as insertion or removal cause reallocation and resizing. In such cases, the vector may internally allocate a new block of memory and copy/move the elements to it.

Bold Text Example:

For example, suppose we have a std::vector<int> called numbers. We can access the third element of the vector using the following code:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::cout << numbers[2] << std::endl;
    return 0;

This will output: 3

Underlined Text Example:

We can also use iterators to iterate over the elements of a std::vector. Here’s an example that prints all the elements in a vector:

int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};

for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << ” “;

return 0;

This will output: 1 2 3 4 5

List Example:

We can add elements to a std::vector using the push_back() function. Here’s an example that demonstrates how to add elements to a vector:

int main() {
std::vector<int> numbers;

for (auto it = numbers.end(); ++it) {
std::cout << *it << ” “;

return 0;

This will output:

  • 1 2 3

In conclusion, std::vector is a versatile data structure in C++ that provides dynamic sizing, efficient random access, and seamless integration with the C++ Standard Library. Understanding its underlying data structure helps developers make informed design decisions and optimize their code.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy