This tutorial will discuss how to add elements into a vector in C++.

We can create an empty vector like this:

std::vector<int> vecObj;

Here, we’ve created an empty vector of integers. If you call the size() function on this vector, it will return zero because it does not contain any elements. But what if we want to insert elements into it? In that case, we can use the push_back() function of the vector. The push_back() function accepts an element as an argument and appends that element to the end of the vector. In the following code, we insert 3 different elements into the vector by calling the push_back function multiple times:

myVector.push_back(5);
myVector.push_back(15);
myVector.push_back(25);

Now, the size of the vector is 3 because we’ve added 3 elements to it. We can confirm this either by iterating over the vector or by calling its size() function.
Contents of the vector will be like,

5, 15, 25

In the example below, we create an empty vector, add 3 different elements using the push_back function, print its size, and finally use a range-based for loop to iterate over and print its elements:

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    // Creating an empty vector
    std::vector<int> vecObj;

    // Add elements to the end of Vector
    vecObj.push_back(5);
    vecObj.push_back(15);
    vecObj.push_back(25);

    std::cout << "Size of Vector: " << vecObj.size() << std::endl;

    std::cout << "Contents of Vector: ";
    for (const auto &num : vecObj)
    {
        std::cout << num << ", ";
    }
    std::cout << "n";

    return 0;
}

Output

Size of Vector: 3
Contents of Vector: 5, 15, 25,

This code initializes an empty vector, adds 3 integers to it, prints its size, and then iterates over its elements to print each one.

Summary

Today, we learned how to add elements into a vector in C++.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.