Open In App

How to copy elements of an Array in a Vector in C++

Last Updated : 27 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.

Array

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

Following are the different ways to copy elements from an array to a vector:

Method 1: Naive Solution
Traverse the complete array and insert each element into the newly assigned vector using the push_back() function. Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    // Initialise an array
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Initialize an empty vector
    vector<int> v;
  
    // Traverse the array and
    for (int i = 0; i < N; i++)
        v.push_back(arr[i]);
  
    // Print all elements of vector
    for (auto ele : v) {
        cout << ele << " ";
    }
  
    return 0;
}


Output

1 2 3 4 5 

Method 2: Range-based Assignment during Initialization
In C++, the Vector class provides a constructor which accepts a range, so to create a vector from array elements, pass the pointer to the first and last position of the range as the argument during the vector initialization that needs to be copied to the vector i.e, (arr, arr+N).

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    // Initialise an array
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Initialize a vector by passing the
    // pointer to the first and last element
    // of the range as arguments
    vector<int> v(arr, arr + N);
  
    // Print all elements of vector
    for (auto ele : v) {
        cout << ele << " ";
    }
  
    return 0;
}


Output

1 2 3 4 5 

Note that Iterators used to point at the memory addresses of STL containers can also be used.

  • std::begin(arr)- Iterator to the first element of an array.
  • std::end(arr)- Iterator to the one after the last element of an array.

vector<int> v(begin(arr), end(arr));

Method 3: Using Inbuilt Function Insert(position, first_iterator, last_iterator): The insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. Instead of a single value, a range can also be passed as arguments.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    // Initialise an array
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Initialize an empty vector
    vector<int> v;
  
    // Add array elements in the required
    // range into a vector from beginning
    v.insert(v.begin(), arr, arr + N);
  
    // Print all elements of vector
    for (auto ele : v) {
        cout << ele << " ";
    }
  
    return 0;
}


Output

1 2 3 4 5 

Method 4: Using Inbuilt Function Copy(first_iterator, last_iterator, back_inserter()): This is another way to copy array elements into a vector is to use the inbuilt copy function. This function takes 3 arguments, an iterator to the first element of the array, an iterator to the last element of the array, and the back_inserter function to insert values from the back.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    // Initialise an array
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Initialize an empty vector
    vector<int> v;
  
    // Copy array elements in the required
    // range into vector v using copy function
    copy(begin(arr), end(arr), back_inserter(v));
  
    // Print all elements of vector
    for (auto ele : v) {
        cout << ele << " ";
    }
  
    return 0;
}


Output

1 2 3 4 5 

Method 5: Using Inbuilt Function Assign( first_iterator, last_iterator ): The vector::assign() function can be used to assign values to a new vector or an already existing vector. It can also modify the size of the vector if necessary. It takes the iterator to the first and last position as arguments.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    // Initialise an array
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Initialize an empty vector
    vector<int> v;
  
    // Assign the elements of the array
    // into the vector v
    v.assign(arr, arr + N);
  
    // Print all elements of vector
    for (auto ele : v) {
        cout << ele << " ";
    }
  
    return 0;
}


Output

1 2 3 4 5 

Method 6: Using Inbuilt Function Transform(first_iterator, last_iterator, back_insert(), function): The std::transform() function takes 4 arguments, an iterator to the first element of the array, an iterator to the last element of the array, the back_inserter function to insert values from the back and a user-defined function which can be used to modify all the elements of the array i.e, perform a unary operation, convert lower case characters to upper case, etc.

Below is the implementation of the above approach:

C++14




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to increment the value by 1
int increment(int x)
{
    return x + 1;
}
  
// Driver code
int main()
{
    // Initialise an array
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Initialize an empty vector
    vector<int> v;
  
    // Copy the elements of the array into
    // vector v and increment each value
    transform(arr, arr + N, back_inserter(v), increment);
  
    // Print all elements of vector
    for (auto ele : v) {
        cout << ele << " ";
    }
  
    return 0;
}


Output

2 3 4 5 6 


Similar Reads

How to Copy a Vector to an Array in C++?
In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. Sometimes, we may need to copy the contents of a vector to the POD array. In this article, we will learn how to copy a vector to an array in C++. Example: Input: myVec = {10,20,30,40,50,60};Output: array: {10,20,30,40,50,60}Convert Vector to an Array in C++ For
2 min read
Shallow Copy and Deep Copy in C++
In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. Copy ConstructorDefault assignment operator // Copy ConstructorGeeks Obj1(Obj);orGeeks Obj1 = Obj; // Default assignment operatorGeeks Obj2;Obj2 = Obj1; Depending upon the resources like dynamic memory hel
5 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header &lt;algorithm&gt;. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Copy File To Vector in C++ STL
Prerequisite: Vectors in C++ STLFile Handling in C++ The C++ Standard Template Library (STL) provides several useful container classes that can be used to store and manipulate data. One of the most commonly used container classes is the vector. In this article, we will discuss how to copy the contents of a file into a vector using C++ STL. Approach
2 min read
Ways to copy a vector in C++
In the case of arrays, there is not much choice to copy an array into another, other than the iterative method i.e running a loop to copy each element at its respective index. But Vector classes have more than one method for copying entire vectors into others in easier ways. There are basically two types of copying:- Method 1: Iterative method. Thi
7 min read
vector::front() and vector::back() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::front() This function can be used to fetch the first element of a vector container.Syntax : vectorname.front() Parameters : No value is needed to pass as
3 min read
vector::empty() and vector::size() in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::empty() The empty() function is used to check if the vector container is empty or not.Syntax : vectorname.empty() Parameters : No parameters are p
5 min read
vector::push_back() and vector::pop_back() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::push_back() push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the cur
4 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator= This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
vector::at() and vector::swap() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::at() at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameter
4 min read
Article Tags :
Practice Tags :