Lesson 21 of 45 · C++
Lesson 28: Vector Container
Duration: 12 min
Lesson 21 of 45 · C++
Duration: 12 min
std::vector is the go‑to dynamic array in C++. It stores elements contiguously, supports random access, and automatically manages its memory.\n\n---\n\n## Core operations\n- Construction – default, size initialisation, initializer list.\n- Capacity management – size(), capacity(), reserve(), shrink_to_fit().\n- Element access – operator[], at(), front(), back(), data().\n- Modifiers – push_back(), emplace_back(), pop_back(), clear(), insert(), erase().\n\n---\n\n## Example: Building a histogram with a vector\ncpp\nstd::vector<int> histogram(10, 0); // 10 bins initialised to 0\nint value;\nwhile (std::cin >> value) {\n if (value >= 0 && value < 10) ++histogram[value];\n}\nfor (std::size_t i = 0; i < histogram.size(); ++i) {\n std::cout << i << ": " << histogram[i] << '\\n';\n}\n\n\nNotice how reserve can prevent reallocations when you know the final size:\ncpp\nstd::vector<int> data;\ndata.reserve(1000); // allocate space for 1000 ints up front\n\n\n> Tip: Prefer emplace_back when constructing an object directly inside the vector to avoid extra moves or copies.\n\n---\n\n<Alert type="warning">When a vector grows, it may reallocate, invalidating all iterators and references to its elements.