Ad space (banner)
Lesson 14 / 20

Using vector (the Standard Library)

This lesson covers vector โ€” an array whose size can freely change. It's for anyone searching "C++ vector usage."

std::vector<type> is a resizable array provided by C++'s standard library. Add an element with push_back(), and get the element count with size().

The example creates std::vector<std::string> fruits;, adds fruits with push_back(), then displays every element with a range-based for loop (for (auto& f : fruits)).

A common early mistake is being unsure when to use this versus the regular array from cpp-06. The rule of thumb: use an array when the element count is fixed ahead of time, and a vector when it might grow or shrink while the program runs.

In real projects, vector โ€” safer and more feature-rich than a raw, C-style array โ€” is the standard choice.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)