Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 21 of 45 · C++

Lesson 28: Vector Container

Duration: 12 min

Vector Container\n\nstd::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.

Previous: Lesson 27: Standard Template Library (STL) OverviewNext: Lesson 29: List Container