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

Related Tutorials



Comments and Discussions!

Load comments ↻





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