Vector in C++ (STL)

In this article, we will discuss what is a std::vector<> and how to use it in C++.

What is a vector in C++?

A vector is a STL Container, which acts like a dynamic array. It can grow or shrink as needed, and provides a number of useful member functions for working with the elements in it.

How vector stores the data internally?

A vector in C++, stores its data internally using a contiguous block of memory, just like an array. But array is of fixed size, whereas as the size of vector is dynamic in nature. What does that mean?

When a vector is created, it initially reserves a small amount of memory to store its elements. As elements are added to the vector, it dynamically resizes itself by allocating more memory as needed. Therefore, it is also called as dynamic array.

The vector stores the elements in the contiguous block of memory, and keeps track of the number of elements currently stored in the vector using a “size” member variable. It also keeps track of the amount of memory currently allocated for the vector using a “capacity” member variable.

When the number of elements stored in the vector exceeds the current capacity, the vector automatically resizes itself by allocating a new block of memory that is large enough to store the additional elements. This process is known as reallocation, and it can be done by copying the elements from the old block of memory to the new block of memory.

How to create a vector in C++?

First we need to include the “vector” header file. Then we can declare a vector object by specifying the type of elements it will store.



    #include <vector>
    
    std::vector<type> vecObj;
    

    The type here, can be int, char, string or any other valid type. Once we declare a vector object with the a type, then that vector object can store elements of that type only. For example,

    std::vector<int> vecOfNumbers;
    

    This a vector of integers, and it can store integers only.

    std::vector<std::string> vecOfStr;
    

    This a vector of strings, and it can store strings only.

    std::vector<char> vecOfChar;
    

    This a vector of strings, and it can store strings only.

    We don’t need to provide the size of vector while declaring its object, because vector is dynamics in nature. It means it can grow automatically when we add elements in it, also it can shrink automatically when we delete elements from it.

    Let’s a complete C++ program, to create a vector of integers:

    #include <vector>
    
    int main() {
        std::vector<int> vecObj;
        return 0;
    }
    

    It will create am empty vector object. Its size will be zero.

    You can also create a vector and initialize it with a set of elements at the time of creation. For example:

    #include <iostream>
    #include <vector>
    
    int main() 
    {
        std::vector<int> vecObj = {11, 12, 13, 14, 15};
    
        for(auto& elem: vecObj)
        {
            std::cout << elem << ", ";
        }
        std::cout<< std::endl;
    
        return 0;
    }
    

    Output:

    11, 12, 13, 14, 15,
    

    Here we passed an initializer_list to the vector contsructor, and the vector got initialised with five integers, and then we iterated over the vector, using a range based for loop, and printed its elements.

    Initialize a vector with n copies of same element

    In C++, std::vector class provides a constructor vector(n, element), and it creates a vector object, initialised with n copies of the given element.

    For example,

    #include <iostream>
    #include <vector>
    
    int main() {
    
        // Initialize a vector with 10 copies of integer 5
        std::vector<int> numbers(10, 5);
    
        // Iterate over vector and print its contents
        for (const int& num: numbers)
        {
            std::cout<<num << ", ";
        }
        std::cout<< std::endl;
    
        return 0;
    }
    

    Output:

    5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    

    Here, we created a vector of integers and initialised it with the ten repeated integer values i.e. 5.

    Create an empty vector object and append elements

    We can create an empty vector by just specifying the type while creating the object. Then we can add elements to it using the push_back() function. Basically, the vector::push_back(element) function adds a new element at the end of the vector. Let’s see complete example,

    #include <iostream>
    #include <vector>
    
    int main() {
    
        // Create an empty vector
        std::vector<int> numbers;
    
        if (numbers.empty())
        {
            std::cout<<"Vector is empty" <<std::endl;
        }
    
        // Add five elements to vector one by one
        numbers.push_back(11);
        numbers.push_back(12);
        numbers.push_back(13);
        numbers.push_back(14);
        numbers.push_back(15);
    
    
        // Iterate over vector and print its contents
        for (const int& num: numbers)
        {
            std::cout<<num << ", ";
        }
        std::cout<< std::endl;
    
        return 0;
    }
    

    Output:

    Vector is empty
    11, 12, 13, 14, 15,
    

    We created an empty vector of integers and then checked if it is empty or not using the empty() function. After that we added five integers in it.

    C++ vector Operations

    How to get the size of vector?

    In C++, the vector class provides a member function vector::size(), and it returns the number of elements in the vector. It might be possible that vector has the much larger capacity to store more elements, but the size() function will only return the actual stored elements in the vector. For an empty vector it will return 0. Let’s see an example,

    #include <iostream>
    #include <vector>
    
    int main() {
    
        // Initialize a vector with initializer_list
        std::vector<int> numbers = {11, 22, 33, 44, 55};
    
        size_t len = numbers.size();
    
        std::cout<< "Number of elements in vector are : " << len <<std::endl;
    
        return 0;
    }
    

    Output:

    Number of elements in vector are : 5
    

    We initialised the vector with five elements, therefore the size() function returned the value 5.

    Summary

    We learned about the usage details of STL Container Vector in C++.

    Scroll to Top