Convert an array to a vector in C++

In this post, we will discuss how to convert an array to a vector in C++.

 

1. 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 simplest and very efficient solution.

 

Download   Run Code

Output:

1 2 3 4 5

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

 

Download   Run Code

Output:

1 2 3 4 5

 

2. std::insert

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

 

Download   Run Code

Output:

1 2 3 4 5

 

3. Naive

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 push_back() method.

 

Download   Run Code

Output:

1 2 3 4 5

 

4. std::copy

We can also use 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 vector has enough space, we can simply specify output iterator the beginning of the destination range.

 

Download   Run Code

Output:

1 2 3 4 5

 

5. memcpy()

Since vector is nothing but a dynamic array, 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. std::assign

We can also use 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

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of