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

Copy std::vector into std::array

本文关键字:std array vector 复制      更新时间:2023-10-16

如何将std::vector<T>的第一个n元素复制或移动到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中包装源迭代器。

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

您可以使用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());

这是现场示例。

如果要移动,则可以使用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());

这是另一个活的例子。