×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Create an empty vector and initialize by pushing values in C++ STL

C++ STL Vector Initialization: Here, we are going to learn how to create an empty vector and how to initialize it by pushing the values in C++ STL?
Submitted by IncludeHelp, on May 12, 2019

What is the vector?

Vector is a container in C++ STL, it is used to represent array and its size can be changed.

Read more: C++ STL Vector

Creating an empty vector

Here is the syntax to declare an empty vector,

vector<type> vector_name;

Here,

  • type – is the datatype.
  • vector_name – is any use defined name to the vector.

Example to create/declare an empty vector of int type

vector::<int> v1;

Initialize vector by pushing the element

To insert an element in the vector, we can use vector::push_back() function, it inserts an element at the end of the vector.

Syntax:

vector_name.push_back(element);

Example:

v1.push_back(10);
v1.push_back(10);
.
.

C++ STL program to create an empty vector and initialize by pushing values

//C++ STL program to create an empty vector 
//and initialize by pushing values
#include <iostream>
#include <vector>
using namespace std;

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

    //pushing the elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    //printing the vector elements
    //creating iterator to access the elements
    vector<int>::iterator it;
    cout << "Vector v1 elements are: ";
    for (it = v1.begin(); it != v1.end(); it++)
        cout << *it << " ";
    cout << endl;

    return 0;
}

Output

Vector v1 elements are: 10 20 30 40 50

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.