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

时间:2022-04-07 04:26:19

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

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

2 个解决方案

#1


27  

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 :: move_iterator中。

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

#2


4  

You can use std::copy:

你可以使用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:

如果你想移动,你可以使用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.

这是另一个实例。

#1


27  

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 :: move_iterator中。

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

#2


4  

You can use std::copy:

你可以使用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:

如果你想移动,你可以使用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.

这是另一个实例。