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?

问题评论:

答案:

答案1:

std::vector<char> myvector { myData.begin(), myData.end() };

答案评论:

答案2:

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());

答案评论:

答案3:

I’d use the range constructor of vector – looking like myvector(myData.begin(), myData.end())

for future reference:
http://en.cppreference.com/w/cpp/container/vector/vector

答案评论:

答案4:

Just for variety:

std::vector<char> myvector(std::begin(myData), std::end(myData);

答案评论:

原文地址:

https://stackoverflow.com/questions/47754679/how-to-convert-a-stdarray-to-a-stdvector

添加评论

友情链接:蝴蝶教程