The Wayback Machine - https://web.archive.org/web/20250330220949/https://www.geeksforgeeks.org/vector-push-back-cpp-stl/
Open In App

Vector push_back() in C++ STL

Last Updated : 27 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In C++, the vector push_back() is a built-in method used to add a new element at the end of the vector. It automatically resizes the vector if there is not enough space to accommodate the new element.

Let’s take a look at an example that illustrates the vector push_back() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 4, 6};

    // Add an element at the end of the vector
    v.push_back(9);

    for (int i : v)
        cout << i << " ";
    return 0;
}

Output
1 4 6 9 

This article covers the syntax, usage, and common examples of the vector push_back() method in C++:

Syntax of Vector push_back()

The vector push_back() is a member method of the std::vector class defined inside the <vector> header file.

v.push_back(val);

Parameters:

  • val: Element to be added to the vector at the end.

Return Value:

  • This function does not return any value.

Examples of vector push_back()

The following examples demonstrate the use of the vector push_back() function for different purposes:

Initialize an Empty Vector One by One

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

    // Add elements to the vector
    v.push_back(3);
    v.push_back(7);
    v.push_back(9);

    for (int i : v)
        cout << i << " ";
    return 0;
}

Output
3 7 9 

Add Elements Vector of Strings at the End

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<string> v = {"Hello", "Geeks"};

    // Add string to the vector
    v.push_back("Welcome");

    for (string s: v) 
        cout << s << " ";
    return 0;
}

Output
Hello Geeks Welcome 

Vector push_back() in C++ – FAQs

What happens if a vector’s capacity is exceeded while using push_back()?

When the number of elements in a vector exceeds its current capacity, the vector reallocates memory, usually doubling its capacity, to accommodate new elements.

Can we use push_back() to add elements to a specific position?

No, push_back() always adds an element at the end of the vector. To insert at a specific position, use the vector insert() function.

Does push_back() work for user-defined objects?

Yes, as long as the user-defined object supports copying or moving, it can be added to a vector using push_back().

What is the time complexity of push_back() function?

The amortized time complexity of vector push_back() is O(1).



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg