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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 28: Vector Container | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 28 of 45

·C++

Lesson 28: Vector Container

12 min

Course progress62%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Construction, sizing, and capacity management
  • Element access and modifiers
  • Iterators and range‑based for
  • Performance considerations (reallocation, shrink‑to‑fit)

Vector Container

std::vector is the go‑to dynamic array in C++. It stores elements contiguously, supports random access, and automatically manages its memory.


Core operations

  • Construction – default, size initialisation, initializer list.
  • Capacity management – size(), capacity(), reserve(), shrink_to_fit().
  • Element access – operator[], at(), front(), back(), data().
  • Modifiers – push_back(), emplace_back(), pop_back(), clear(), insert(), erase().

Example: Building a histogram with a vector

std::vector<int> histogram(10, 0); // 10 bins initialised to 0
int value;
while (std::cin >> value) {
    if (value >= 0 && value < 10) ++histogram[value];
}
for (std::size_t i = 0; i < histogram.size(); ++i) {
    std::cout << i << ": " << histogram[i] << '\
';
}

Notice how reserve can prevent reallocations when you know the final size:

std::vector<int> data;
data.reserve(1000); // allocate space for 1000 ints up front

Tip: Prefer emplace_back when constructing an object directly inside the vector to avoid extra moves or copies.


<Alert type="warning">When a vector grows, it may reallocate, invalidating all iterators and references to its elements.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 27: Standard Template Library (STL) OverviewContinue to lesson 29Lesson 29: List ContainerBack to C++ Course curriculum