×

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 a vector and initialize it like an array in C++ STL

C++ STL | vector creation and initialization like an array: Here, we are going to learn how to create a vector and initialize it like an array 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

Create a vector and initializing it like an array

We can also initialize a vector like an array in C++ STL. Here, we are going to learn the same, how can we initialize a vector like an array?

Here is the syntax to create and initialize a vector like an array,

    vector<type> vector_name{element1, element2, ...};

Here,

  • type – is the datatype.
  • vector_name – is any use defined name to the vector.
  • element1, element2, ... – elements to initialize a vector.

Example to create/declare and initialize vector like an array

    vector::<int> v1{ 10, 20, 30, 40, 50 };

C++ STL program to create and initialize a vector like an array

//C++ STL program to create and initialize 
//a vector like an array 
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration and initialization
    //like an array
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing the vector elements
    //using for each kind of loop
    cout << "Vector v1 elements are: ";
    for (int element : v1)
        cout << element << " ";
    cout << endl;

    //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
    //using for each kind of loop
    cout << "After pushing the elements\nVector v1 elements are: ";
    for (int element : v1)
        cout << element << " ";
    cout << endl;

    return 0;
}

Output

Vector v1 elements are: 10 20 30 40 50
After pushing the elements
Vector v1 elements are: 10 20 30 40 50 10 20 30 40 50

Related Tutorials

Comments and Discussions!

Load comments ↻





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