Copy std::vector into std::array

妖精的绣舞 提交于 2019-12-18 18:39:45

问题


How do I copy or move the first n elements of a std::vector<T> into a C++11 std::array<T, n>?


回答1:


Use std::copy_n

std::array<T, N> arr;
std::copy_n(vec.begin(), N, arr.begin());

Edit: I didn't notice that you'd asked about moving the elements as well. To move, wrap the source iterator in std::move_iterator.

std::copy_n(std::make_move_iterator(v.begin()), N, arr.begin());



回答2:


You can use std::copy:

int n = 2;
std::vector<int> x {1, 2, 3};
std::array<int, 2> y;
std::copy(x.begin(), x.begin() + n, y.begin());

And here's the live example.

If you want to move, instead, you can use std::move:

int n = 2;
std::vector<int> x {1, 2, 3};
std::array<int, 2> y;
std::move(x.begin(), x.begin() + n, y.begin());

And here's the other live example.



来源:https://stackoverflow.com/questions/21276889/copy-stdvector-into-stdarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!