Home » C++ STL

Create a vector and initialize it from an array in C++ STL

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

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

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

    vector<type> vector_name(array_name_from, array_name_to);

Here,

  • type – is the datatype.
  • vector_name – is any use defined name to the vector.
  • array_name_from, array_name_to – from and to indexes of the array.

Example to create/declare and initialize vector from an array

    vector<int> v1(iarr, iarr + size);

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

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

int main()
{
    //array declaration
    int iarr[] = { 10, 20, 30, 40, 50 };

    //vector declaration and initialization
    //form a given array
    //first finding the size of the array
    int size = sizeof(iarr) / sizeof(iarr[0]);

    vector<int> v1(iarr, iarr + size);

    //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





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.