将std :: vector复制到std :: array
Copy std::vector into std::array
如何将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());
这是另一个活的例子。
相关文章:
- C++11 中不同类型的对象的 std::array 的替代方案
- constexpr begin of a std::array
- C++如果必须在编译时确定大小,std::array 有什么意义?
- 标准::unordered_map 中的 std::array 的值初始化
- 确保编译时的特定 std::array 位置
- std::array的长度有大小限制吗?
- 将 std::array 移动到另一个 std::array
- 检查输入 std::array 指针数据是否等于某个常量数组
- 如何读/写或遍历 std::array 中的特定元素范围?
- 是否可以使用 std::array 作为 POD 结构的数据容器?
- 如何在C++中传递一个大小未知的 std::array?
- 将 std::array 推回 std::vector N 次的优雅方式
- 如何在 c++11 中静态断言 std::array 类成员进行排序?
- unqualified sort() -- 为什么它在 std::vector 上使用而不是在 std::array 上
- 按值返回 std::array
- 如何将变量内容常量转换为 std::array 的大小?
- 将初始化器列表/聚合初始化转发到 std::array 成员
- 无法推断类中的类型,构造函数采用 std::array
- 为什么 char 可以在 std::array 中初始化为 nullptr,而不是单独初始化?
- C++ IDE 不会推断/自动完成对模板类中的 std::array 下标表达式的成员访问