Thuta Learning
AdvancedProgrammingbeginner

STL: Vector

Relax. We'll talk through this in plain words — no textbook voice.

Vector is the dynamic array from the C++ Standard Template Library (STL). Like an array, you can access items by index, but you can also grow or shrink the item count at runtime. When you don't know the item count up front based on user input, vector is a better fit than a plain array.

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

int main() {
    vector<string> tasks;

    tasks.push_back("Learn variables");
    tasks.push_back("Practice loops");
    tasks.push_back("Build a mini project");

    for (string task : tasks) {
        cout << "- " << task << endl;
    }

    cout << "Total tasks: " << tasks.size();
    return 0;
}

vector<string> is a vector that stores string items. push_back() adds a new item, and a range-based for loop makes it easy to read out every item. size() returns the item count.

You should see
- Learn variables - Practice loops - Build a mini project Total tasks: 3

Info

In modern C++, vector is heavily used for list data that doesn't need a fixed size. It's more flexible than an array and pairs nicely with STL algorithms too.

Easy traps

  • tasks[tasks.size()] is an invalid index. If you want the last item, use tasks[tasks.size() - 1] or tasks.back().
STL: Vector | Thuta Learning