C++:C++ std::vector (Dynamic Arrays): Methods and Memory
C++•Vectors & Arrays

C++ std::vector (Dynamic Arrays): Methods and Memory

std::vector is the default sequence container in modern C++, offering dynamic resizing and contiguous cache-friendly memory.

Syntax

#include <vector> std::vector<int> numbers = {1, 2, 3}; numbers.push_back(4);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
push_back(val)MethodAppends element to end of vector.
at(index)MethodAccesses element with bounds-checking (throws std::out_of_range).

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> scores = {92, 85, 88};

    // Dynamically append items
    scores.push_back(95);
    scores.push_back(99);

    std::cout << "Vector Size: " << scores.size() << "\n";
    std::cout << "Capacity:    " << scores.capacity() << "\n";

    // Safe bounds-checked access
    std::cout << "First Score: " << scores.at(0) << "\n";
    std::cout << "Last Score:  " << scores.back() << "\n";

    // Sum using std::accumulate
    int sum = std::accumulate(scores.begin(), scores.end(), 0);
    std::cout << "Total Sum:   " << sum << "\n";

    return 0;
}
Expected Output:
Vector Size: 5
Capacity:    6
First Score: 92
Last Score:  99
Total Sum:   459

How It Works: Step-by-Step

  • Lines 5-9: Initializes vector and appends elements dynamically.
  • Lines 14-15: Uses at() for safe bounds checking and back() for last element.
  • Line 18: Computes sum using <numeric> std::accumulate.

Key Concepts

  • std::vector elements are contiguous in memory, providing O(1) random access.
  • size() is current element count; capacity() is allocated buffer size before reallocation.
  • at(i) throws std::out_of_range exception if index is invalid; operator[] does not check bounds.

Common Mistake: Using operator[] beyond vector size

vector[i] does not perform bounds checking and causes undefined memory behavior on invalid indices.

❌ Incorrect
std::vector<int> v;
v[0] = 10; // Undefined Behavior: capacity is 0!
✅ Correct
std::vector<int> v;
v.push_back(10); // Resizes safely

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler