C++ Vector push_back

To add elements to vector, you can use push_back() function.

push_back() function adds the element at the end of this vector. Thus, it increases the size of vector by one.

Example 1: Add Element to Vector

In this example, we will define a Vector of Integers, and add an integer to this vector using push_back() function.

C++ Program

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

int main() {
   vector<int> nums;
   nums.push_back(24);
   nums.push_back(81);
   nums.push_back(57);

   for(int num: nums)
      cout << num << " ";
}

Initially, when we declared the vector, there are no elements in it. The size of vector is zero.

When we added first element 24, the element is added as the first element in the vector.

When we added second element 81, the element is added as the second element in the vector. In other words, after the current last element 24 which is first element. And so on for other elements.

Output

24 81 57

Storage of Vector in Memory

Elements of a Vector are stored in continuous memory location. So, when you try to add an element to the vector, and if next memory location is not available, whole vector is copied into a new location with more capacity and the element is added to the existing elements of vector at the end.

Conclusion

In this C++ Tutorial, we learned how to add an element to the existing vector at the end, using push_back() function.