This post will discuss how to convert an array to a vector in C++.

1. Using Range Constructor

The idea is to use the vector’s range constructor that constructs a vector from elements of the specified range defined by two input iterators. This is the simplest and very efficient solution.

Download  Run Code

Output:

1 2 3 4 5

 
The above program uses the sizeof operator for calculating the size of the array. We can avoid that in C++11, which introduced std::begin and std::end functions that return an iterator pointing to the beginning and the end of a sequence.

Download  Run Code

Output:

1 2 3 4 5

2. Using std::insert function

Another efficient solution is to use the std::insert function. std::vector has an overloaded version of std::insert, which takes three parameters – the first parameter is an iterator to the destination vector, and the last two parameters are the iterators specifying a range of array elements.

Download  Run Code

Output:

1 2 3 4 5

3. Naive Solution

A naive solution is to use the simple for-loop that iterates the array and add all its values to the vector one at a time using the push_back() function.

Download  Run Code

Output:

1 2 3 4 5

4. Using std::copy function

We can also use the std::copy STL algorithm, which copies the specified range of elements to another range beginning from the specified output iterator. Since we need to insert new elements at the end of the destination vector, we can use std::back_inserter to the initial position in the destination.

Download  Run Code

Output:

1 2 3 4 5

 
If the vector has enough space, we can simply specify the output iterator to the beginning of the destination range.

Download  Run Code

Output:

1 2 3 4 5

5. Using memcpy() function

Since the vector is nothing but a dynamic array, the memcpy() function can also work here. It performs a binary copy of the data and hence is error-prone. It can be used with arrays of POD (Plain Old Data) type like int, char, etc., but not recommended with structs or classes.

Download  Run Code

Output:

1 2 3 4 5

6. Using std::assign function

We can also use the std::assign function that replaces the existing contents of the vector with elements of the specified range.

Download  Run Code

Output:

1 2 3 4 5

That’s all about converting an array to a vector in C++.