C++ Vectors


Vectors are one of the most commonly used data structures in C++. They belong to the Standard Template Library (STL) and work as dynamic arrays that can grow or shrink in size automatically. Unlike regular arrays that have a fixed size, vectors manage memory on their own and make working with collections of data much easier.

In this tutorial, you’ll learn everything about C++ vectors — how they work, how to create and modify them, and what makes them so powerful.

What Is a Vector in C++?

A vector is a dynamic array that can change its size when new elements are inserted or existing ones are removed. It is defined in the <vector> header and is part of the std namespace.

Vectors are useful because they offer both array-like random access and automatic memory management.

Basic Syntax

#include <vector>
vector<data_type> vector_name;

Example

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};
    numbers.push_back(40);
    numbers.push_back(50);

    for (int n : numbers)
        cout << n << " ";
    return 0;
}

Output:

10 20 30 40 50

How to Declare and Initialize Vectors

You can create vectors in several ways depending on your requirements.

Different Initialization Methods

  1. Empty vector

    vector<int> v;
    
  2. Vector with fixed size and default values

    vector<int> v(5); // 5 elements initialized to 0
    
  3. Vector with fixed size and custom value

    vector<int> v(4, 100); // 4 elements, each initialized to 100
    
  4. Copy from another vector

    vector<int> v1 = {1, 2, 3};
    vector<int> v2(v1);
    
  5. Initialize using array

    int arr[] = {5, 10, 15};
    vector<int> v(arr, arr + 3);
    

Accessing Vector Elements

Vectors provide different ways to access elements safely and efficiently.

Common Methods

  • Using index operator [ ]

    cout << v[0];
    
  • Using at() method (safe access)

    cout << v.at(2);
    
  • Accessing first and last element

    cout << v.front(); // First element
    cout << v.back();  // Last element
    

Example

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums = {10, 20, 30, 40};
    cout << "First element: " << nums.front() << endl;
    cout << "Last element: " << nums.back() << endl;
    cout << "Element at index 2: " << nums.at(2) << endl;
    return 0;
}

Output:

First element: 10  
Last element: 40  
Element at index 2: 30  

Adding and Removing Elements

Vectors support easy insertion and deletion using built-in functions.

Commonly Used Functions

  • push_back(value) – Adds element at the end.

  • pop_back() – Removes last element.

  • insert(position, value) – Inserts at a specific position.

  • erase(position) – Removes an element at a specific position.

  • clear() – Removes all elements.

Example

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums = {10, 20, 30};
    nums.push_back(40);
    nums.pop_back();
    nums.insert(nums.begin() + 1, 15);

    for (int n : nums)
        cout << n << " ";
    return 0;
}

Output:

10 15 20 30

Iterating Through a Vector

You can loop through a vector using different techniques.

1. Using a for loop

for (int i = 0; i < nums.size(); i++)
    cout << nums[i] << " ";

2. Using range-based for loop

for (int n : nums)
    cout << n << " ";

3. Using iterators

for (auto it = nums.begin(); it != nums.end(); ++it)
    cout << *it << " ";

Useful Vector Functions

Here are some of the most commonly used vector functions:

Function Description
size() Returns number of elements in the vector
empty() Checks if the vector is empty
capacity() Returns allocated storage size
resize(n) Changes the number of elements
swap() Exchanges contents of two vectors

Example

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> a = {1, 2, 3};
    vector<int> b = {4, 5};
    a.swap(b);

    cout << "After swap, vector a: ";
    for (int x : a)
        cout << x << " ";
    return 0;
}

Output:

After swap, vector a: 4 5

Vector Memory Management

Vectors automatically handle memory, but you can also control it manually.

  • reserve(n) – Allocates memory for at least ‘n’ elements to prevent frequent reallocations.

  • shrink_to_fit() – Reduces capacity to match the current size.

Example:

vector<int> nums;
nums.reserve(100);

This line pre-allocates memory for 100 elements, improving performance when inserting large data.

Advantages of Using Vectors

  • Automatically resize as elements are added or removed.

  • Support random access using indexes.

  • Integrated with STL algorithms.

  • Easy to copy, insert, and delete elements.

  • Manage memory efficiently.

Summary of the Tutorial

Vectors are one of the most versatile and efficient data structures in C++. They provide the flexibility of dynamic arrays with the simplicity of standard arrays. Since vectors integrate perfectly with STL algorithms and iterators, they are a go-to choice for most modern C++ programs.

Once you master vectors, you’ll find it easier to handle other STL containers like lists, sets, and maps.


Practice Questions

  1. Write a C++ program to create a vector of integers and insert elements using push_back().

  2. Create a program that takes 5 numbers as input from the user and stores them in a vector, then prints them.

  3. Write a program to access and modify the second element of a vector using the at() function.

  4. Build a program that removes the last element of a vector using pop_back() and displays the updated vector.

  5. Write a C++ program that uses a loop to find the sum of all elements in a vector.

  6. Create a program that reverses the elements of a vector using the reverse() algorithm.

  7. Write a program that sorts a vector of strings in alphabetical order using sort().

  8. Build a C++ program that merges two integer vectors into one and displays all elements.

  9. Write a program that demonstrates how to clear all elements of a vector using clear() and check if it’s empty.

  10. Create a program that finds the largest and smallest elements in a vector using max_element() and min_element().


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top