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
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.
这是另一个实例。