HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Vectors (vector)

Vectors (vector)

Flexible arrays: traversing with push_back, size, [] and range-for.

Simple enough for a 5-year-old to understand

create vector and add

Arrays are fixed-size; vector is used for a list that can grow (requires <vector>).

Example code
1
#include <iostream>
2
#include <vector>
3
using namespace std;
4
int main() {
5
vector<int> v = {1, 2};
int vector.
Dataint vector.
6
v.push_back(3);
Add to the end.
CodeAdd to the end.
7
cout << v[0] << " " << v.size() << endl;
1 3
Output / Input1 3
8
return 0;
9
}
DataCodeOutput / Input
💡 Hint: push_back adds an element, size() gives the size, accessed via v[i].

About this topic

vector is C++'s variable-sized array. It keeps elements contiguous in memory, so access is as fast as an array; but unlike an array, it can grow at runtime. It handles size tracking and memory management automatically.

The growth strategy is important: when out of space, vector multiplies its current capacity, allocates a new block, and moves the elements. That's why push-back is amortized constant time, without individual reallocations.

There is a consequence to this move behavior: when vector grows, the addresses of old elements become invalid. A pointer or iterator held to an element dangles after insertion, and using it crashes the program.

What you will learn

  • defining a vector and adding elements
  • the difference between size and capacity
  • two forms of out-of-bounds access
  • why modifying while iterating is forbidden
  • the range-based loop

When to use?

If the number of elements is not known in advance, vector is the right choice and is considered the default container in C++.

If you know how many elements there will be beforehand, reserving capacity with reserve completely eliminates the reallocations that would happen during growth.

If you frequently insert and delete from the middle, vector is inefficient because all subsequent elements are shifted; in that case, list structures are appropriate.

Common mistakes

Wrong

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

int main() {
    vector<int> numbers;
    numbers[0] = 10;
    cout << numbers[0] << endl;
    return 0;
}

vector is empty; writing with square brackets when there are no elements is undefined behavior. Since bounds checking is not performed, the program might not crash and the error shows up much later. push_back is used to add elements.

Correct

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

int main() {
    vector<int> numbers;
    numbers.push_back(10);
    cout << numbers[0] << endl;
    return 0;
}

Wrong

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

int main() {
    vector<int> numbers = {1, 2, 3, 4};
    for (int i = 0; i <= numbers.size(); i++) {
        cout << numbers[i] << endl;
    }
    return 0;
}

There are two errors. The less-than-or-equal condition goes one element past the array. Also, size returns an unsigned type, and comparing it with a signed counter produces a compiler warning. The range-based loop eliminates both issues.

Correct

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

int main() {
    vector<int> numbers = {1, 2, 3, 4};
    for (int n : numbers) {
        cout << n << endl;
    }
    return 0;
}

Wrong

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

int main() {
    vector<int> numbers = {1, 2, 3, 4};
    for (int n : numbers) {
        if (n == 2) {
            numbers.push_back(99);
        }
    }
    cout << numbers.size() << endl;
    return 0;
}

Modifying while iterating invalidates iterators: if the vector grows and moves to a new memory block, the loop reads invalid addresses. No error message is given, the program might crash or read garbage values. Collect changes in a separate container and merge them afterward.

Correct

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

int main() {
    vector<int> numbers = {1, 2, 3, 4};
    vector<int> extra;
    for (int n : numbers) {
        if (n == 2) {
            extra.push_back(99);
        }
    }
    for (int n : extra) {
        numbers.push_back(n);
    }
    cout << numbers.size() << endl;
    return 0;
}

Frequently asked questions

what is the difference between size and capacity?

size tells you how many elements there are, capacity tells you how many elements can fit without a reallocation. Capacity is usually greater than size. Always use size for the number of elements; capacity only matters when tuning performance.

can vector always be used instead of an array?

In practice yes, and vector is the default choice in C++. Since elements sit side by side, access speed is identical to an array. The only difference is that vector holds its own size information, which means a few extra bytes of overhead.

why do I need to be careful when deleting elements?

Deleting from the middle shifts all subsequent elements back by one, meaning it takes time proportional to the number of elements. Also, iterators after the deleted position become invalid. If you are deleting inside a loop, you must use the iterator returned by erase.

Summary

vector is a variable-sized array and manages its memory by itself.

push_back is used to add elements; an empty container cannot be written to using an index.

Range-based loops completely prevent bounds errors.

Adding or removing elements while iteration is ongoing invalidates iterators.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code