How Does a Vector Work in C++



In C++, a vector is a dynamic array that can grow or shrink automatically. It can store elements in a row (contiguous memory) and resizes itself when needed. When it runs out of space, it creates a bigger array, copies the old data, and adds the new one. So, you can easily add, remove, or access elements using functions like push_back(), size(), and erase().

Basic Operations (push_back, access)

A vector stores elements in a contiguous memory block. You can add elements using push_back() and access them using [] or at().

Syntax

Following is the syntax is as follows:

vector<type> vec;
vec.push_back(value);
value = vec[index]; // or vec.at(index);

Example

In this program, we create a vector, adds three integers to it and prints the second element as the result.

#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<int> nums;
   nums.push_back(10);
   nums.push_back(20);
   nums.push_back(30);
   cout<< "Second element: "<<nums[1];
   return 0;
}

Following is the output to the above program:

Second element: 20

Dynamic Resizing

Vectors grow in size as more elements are added. When capacity is full, a bigger memory block is allocated, and elements are copied into it automatically.

Syntax

Following is the syntax is as follows:

vector<T>vec;
vec.push_back(value);  // Adds value at the end
vec.size();     // Returns current number of elements
vec.capacity(); // Returns current allocated capacity

Example

In this example, we add numbers 1 to 8 into a vector and prints its size and capacity after each insertion.

#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<int> v;
   for (int i = 1; i <= 8; ++i) {
      v.push_back(i);
      cout<< "Size: "<<v.size()<< ",Capacity: "<<v.capacity()<<endl;
   }
   return 0;
}

Following is the output to the above program:

Size: 1, Capacity: 1
Size: 2, Capacity: 2
Size: 3, Capacity: 4
Size: 4, Capacity: 4
Size: 5, Capacity: 8
Size: 6, Capacity: 8
Size: 7, Capacity: 8
Size: 8, Capacity: 8

Capacity vs Size

Size is the number of elements currently in the vector. Capacity is the number of elements the vector can hold before needing to allocate more memory.

Syntax

Following is the syntax is as follows:

vector<T> vec = {val1, val2, val3};
vec.size();     // Number of elements in the vector
vec.capacity(); // Current allocated memory slots

Example

In this example, we initialize a vector with three elements and print its size and capacity.

#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<int> data = {1, 2, 3};
   cout<<"Size: "<<data.size()<< ", Capacity: "<<data.capacity();
   return 0;
}

Following is the output to the above program:

Size: 3, Capacity: 3
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-04-30T18:22:16+05:30

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements