Home » C++ STL

How to copy array elements to a vector in C++ STL?

C++ STL | copying array elements to a vector: Here, we are going to learn how to copy array elements to a vector using the C++ STL program without using a loop?
Submitted by IncludeHelp, on May 25, 2019

Given an array and we have to copy its elements to a vector in C++ STL.

Copying array elements to a vector

In C++ STL, we can copy array elements to a vector by using the following ways,

  1. Assigning array elements while declaring a vector
    When we declare a vector we can assign array elements by specifying the range [start, end] of an array.
        vector<type> vector_name(array_start, array_end);
    
  2. By using copy function
    copy() function is a library function of algorithm header it can be used to copy an array’s elements to a vector by specifying the array range [start, end] and an iterator pointing to the initial position (from where we want to assign the content) of the vector.
        vector<type> vector_name(size);
        std::copy(array_start, array_end, vector_start_iterator); 
    

Note: To use vector – include <vector> header, and to use copy() function – include <algorithm> header or we can simply use <bits/stdc++.h> header file.

C++ STL program to copy array elements to a vector

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

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

    //assigning array to vector while declaring it
    vector<int> v1(arr + 0, arr + 5);

    //declaring an arrray first
    //and then copy the array content
    vector<int> v2(5);
    copy(arr + 0, arr + 5, v2.begin());

    //printing the vectors
    cout << "vector (v1): ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    cout << "vector (v2): ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

vector (v1): 10 20 30 40 50
vector (v2): 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.