A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/vector-push-back-cpp-stl/ below:

Vector push_back() in C++ STL

Vector push_back() in C++ STL

Last Updated : 27 Dec, 2024

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;
}

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:

Return 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;
}
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 


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4