简体   繁体   中英

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?

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

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

eg

std::array<char,10> myData = {0,1,2,3,4,5,6,7,8,9};
std::vector<char> myvector(myData.begin(), myData.end());
std::vector<char> myvector { myData.begin(), myData.end() };

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

只是为了多样性:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM