Home » C++ STL

vector::push_back() function with example in C++ STL

C++ STL vector::push_back() function: Here, we are going to learn about the push_back() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 15, 2019

C++ vector::push_back() function

vector::push_back() is a library function of "vector" header, it is used to insert/add an element at the end of the vector, it accepts an element of the same type and adds the given element at the end of the vector and increases the size of the vector.

Note: To use vector, include <vector> header.

Syntax of vector::push_back() function

    vector::push_back(value_type n);

Parameter(s): n – is an element to be added at the end of the vector.

Return value: void – In returns nothing.

Example:

    Input:
    vector<int> v1;
    
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    Output:
    //if we print the values
    v1: 20 30 40 50   

C++ program to demonstrate example of vector::push_back() function

//C++ STL program to demonstrate example of
//vector::push_back() function

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

int main()
{
    //vector declaration
    vector<int> v1;

    //inserting elements and printing size
    cout << "size of v1: " << v1.size() << endl;
    v1.push_back(10);
    cout << "size of v1: " << v1.size() << endl;
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);
    cout << "size of v1: " << v1.size() << endl;

    //printing all elements
    cout << "elements of vector v1..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

size of v1: 0
size of v1: 1
size of v1: 5
elements of vector v1...
10 20 30 40 50

Reference: C++ vector::push_back()






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.