将 std::vector 复制到 std::array

2022-01-24 00:00:00 containers c++ c++11

如何将 std::vector<T> 的第一个 n 元素复制或移动到 C++11 std::array<T,n>?

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

推荐答案

使用std::copy_n

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

我没有注意到您也询问过移动元素.要移动,请将源迭代器包装在 std::move_iterator 中.p>

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

相关文章