How to Add an Element in Vector using vector::push_back

Vectors are similar to dynamic arrays in that they can automatically resize themselves when an element is added or removed, and their storage is handled by the container.  Since vector elements are stored in contiguous storage, iterators can access and traverse them. Vectors have data inserted at the top. Since the array can need to be expanded at times, inserting at the end takes longer. And there is no resizing, removing the final element takes the same amount of time every time. In terms of time, inserting and erasing at the start or in the center is linear.

The task is to add element to a vector using pushback function.

Add an item in Vector using push_back function

1)push_back function:

Place elements into a vector from the back using the push back() function. After the current last variable, the new value is inserted into the vector at the top, and the container size is increased by one.

Syntax:

given_vector.push_back(element)

Parameters:

The parameter specifies the value to be inserted at the end.

Return:

Adds the value specified as the parameter to the vector called given_vector at the end.

2)Adding element using push_back

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Creating a string vector
    std::vector<std::string> stringvector;
    // printing the size of vector
    cout << "size of given string vector = "
         << stringvector.size() << endl;
    // adding the elements to the vector using push_back
    stringvector.push_back("hello");
    stringvector.push_back("this");
    stringvector.push_back("is");
    stringvector.push_back("BTechGeeks");
    // printing the size of vector after adding the elements
    cout << "size of given string vector after adding elements "
         << stringvector.size() << endl;
    // print the vector
    for (string value : stringvector)
        cout << value << endl;
    return 0;
}

Output:

size of given string vector = 0
size of given string vector after adding elements 4
hello
this
is
BTechGeeks

Related Programs: