LearnForFree
C++ For Beginners
Lesson

Modern Containers (std::vector)

While C-style arrays are fast, their rigid fixed size makes them impractical when you don't know how many items you will store ahead of time. In modern C++, std::vector (part of the Standard Template Library) is the preferred choice for dynamic lists. A std::vector works like a smart array that automatically resizes itself in memory whenever you add or remove elements. To use it, you must include the <vector> header. Essential std::vector Operations • Declaration: std::vector<type> name; (e.g., std::vector<int> nums = {10, 20, 30};). • .push_back(value): Appends a new element to the end of the vector. • .pop_back(): Removes the last element from the vector. • .size(): Returns the current number of elements stored in the vector. • .at(index) vs. [index]: Both access the element at index, but .at(index) performs bounds checking and safely throws an error if you pass an invalid index, whereas [index] does not. • .empty() & .clear(): .empty() returns true if size is 0; .clear() deletes all elements.
#include <iostream> #include <vector> int main() { // Initialize a vector of integers std::vector<int> scores = {90, 85, 78}; // Add elements dynamically scores.push_back(95); scores.push_back(88); // Remove the last element (88) scores.pop_back(); std::cout << "Total scores: " << scores.size() << "\n"; std::cout << "First score: " << scores.front() << "\n"; std::cout << "Score at index 2 (safe access): " << scores.at(2) << "\n"; // Iterate using a range-based for loop std::cout << "All scores: "; for (int s : scores) { std::cout << s << " "; } std::cout << "\n"; return 0; }

Watch companion video on YouTube

Sign in to save your progress