Vectors
In C++, normal arrays have a fixed size, meaning you can’t change how many elements they hold once they’re created. This can be a problem if you don’t know in advance how many items you’ll need. To solve this, C++ provides std::vector. A vector works like an array, but it can grow or shrink when you add or remove elements.
Defining Vectors
Vectors are part of a library called <vector> and is defined as follows.
#include <vector>
using namespace std;
vector<type> name;nameis the name of the vector.typeis the data type stored in the vector. It can be any valid C++ type (int,double,string, etc).
After defining a vector, the vector is empty (like an array of size 0). To give a vector an initial size, use the following syntax.
#include <vector>
using namespace std;
vector<type> name(size, value);sizeis the number of elements in the vector.valueis the initial value given to all elements in the vector.
Operations on Vectors
Vectors behave similarly to arrays. However, vectors have additional functionalities. Let’s say that we defined a vector named v.
#include <vector>
using namespace std;
vector<int> v;Since v can change in size we use v.size() to get the number of elements in v.
The two main functionalities that make vectors special are v.push_back(x) and v.pop_back().
v.push_back(x)adds the value x to the end of the vector.v.pop_back()removes the last element in the vector.
Here is a table of common operations that can be performed on vectors.
| Function | Description |
|---|---|
v.size() |
Returns the current number of elements in the vector. |
v.push_back(x) |
Appends element x to the end of the vector. |
v.pop_back() |
Removes the last element from the vector. |
v.resize(n) |
Changes the number of elements in the vector to n. If n is larger than the current size of the vector, it adds elements; if it is smaller, it removes excess elements from the end. |
v.clear() |
Removes all elements from the vector. |
Example
Let’s take a look at a code using vectors.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v(3, 5); // defines a vector of size 3 where all elements are 5
v.pop_back(); // removes the last element so v will be {5, 5}
v.push_back(2); // adds an element 2 to the end so v be {5, 5, 2}
v.push_back(1); // adds an element 1 to the end so v be {5, 5, 2, 1}
cout << v.size() << endl; // prints the number of elements in v
for (int i = 0; i < v.size(); i++) {
cout << v[i] << ' '; // prints element at index i
}
}This program will output
4
5 5 2 1
This demonstrates basic vector operations — adding and removing elements — and their effect on both content and size.