In C++, standard arrays have a fixed size. Once you declare int numbers[5];, it can never hold more than 5 elements. The <vector> library solves this by providing dynamic arrays that can automatically shrink or grow in size depending on your needs.
Vectors are the backbone of modern C++ programming and are almost always preferred over raw arrays.
Vectors manage their own memory. You add elements to a vector using the .push_back() method, which safely tacks new data onto the end of the list.
#include <iostream> #include <vector> using namespace std;int main() { // Create an empty vector of integers vector<int> scores;
// Add items dynamically scores.push_back(85); scores.push_back(92); scores.push_back(100);
cout << "The vector has " << scores.size() << " elements.\n"; cout << "The first score is: " << scores[0] << "\n";
return 0; }
Just like arrays and strings, using square brackets (e.g., scores[10]) on an index that doesn't exist will silently fetch garbage memory, causing weird bugs.
The Fix: Use scores.at(10). If the item doesn't exist, it safely throws a clear std::out_of_range error instead of silently corrupting your software.
If you iterate over a vector using a range-based loop and suddenly use .push_back() to add a new element, the underlying memory array might be moved by the operating system to make space. This "invalidates your iterators", causing your program to crash spectacularly. Never change the size of a vector while inside a for loop that iterates over it!
Vectors are templates, meaning they can hold any data type, but you must specify what type they hold using angle brackets. Writing vector scores; is a syntax error. It must be vector<int> scores;.
Which method is used to dynamically add a new element to the end of a vector?