Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a std::array to a std::vector?

I need to convert a std::array to a std::vector, but I could not find anyway to do it quickly. Here is the sample code:

 std::array<char,10> myData={0,1,2,3,4,5,6,7,8,9};

Now I need to create a vector such as:

std::vector<char> myvector;

and initialize it with the array values.

What is the fastest way to do this?

like image 256
mans Avatar asked Dec 11 '17 14:12

mans


People also ask

Can we convert array to vector in C++?

To convert an array to vector, you can use the constructor of Vector, or use a looping statement to add each element of array to vector using push_back() function.

How do you return an array as a vector?

Convert an array into a vector in C++ – begin() / end() std::begin(arr) -> Return an iterator pointing to the first element of the array. std::end(arr) -> Return an iterator pointing to the one after the last element of the array.

How do you use an array as a vector?

Each index of array stores a vector which can be traversed and accessed using iterators. Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators.


3 Answers

You can use the constructor of std::vector taking iterators.

Constructs the container with the contents of the range [first, last).

e.g.

std::array<char,10> myData = {0,1,2,3,4,5,6,7,8,9};
std::vector<char> myvector(myData.begin(), myData.end());
like image 178
songyuanyao Avatar answered Oct 18 '22 22:10

songyuanyao


Just for variety:

std::vector<char> myvector(std::begin(myData), std::end(myData);
like image 34
Pete Becker Avatar answered Oct 18 '22 21:10

Pete Becker


std::vector<char> myvector { myData.begin(), myData.end() };
like image 31
Caleth Avatar answered Oct 18 '22 21:10

Caleth