In standard C++, an array has a fixed size. Once you declare an array of size 5, it cannot hold a 6th element. This limitation is solved by Vectors.
A vector in C++ is a dynamic array provided by the STL. It can automatically resize itself whenever elements are added or removed.
To use a vector, you must include the <vector> library at the top of your program.
#include <vector>// vector<DataType> vectorName; vector<int> numbers;
Vectors are incredibly flexible. You can easily add elements to the end of a vector using .push_back(), and remove the last element using .pop_back().
#include <iostream> #include <vector> using namespace std;int main() { // Create an empty vector of strings vector<string> cars;
// Add elements cars.push_back("Volvo"); cars.push_back("BMW"); cars.push_back("Ford");
// Access the first element cout << "First car: " << cars.front() << "\n";
// Remove the last element ("Ford") cars.pop_back();
// Check the current size cout << "Total cars now: " << cars.size() << "\n";
return 0; }
.size(), .empty(), .clear(), and more.Which function is used to add an element to the end of a vector?