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?
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.
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.
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.
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());
Just for variety:
std::vector<char> myvector(std::begin(myData), std::end(myData);
std::vector<char> myvector { myData.begin(), myData.end() };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With