【问题标题】:Copy std::vector into std::array将 std::vector 复制到 std::array
【发布时间】:2014-01-22 07:38:44
【问题描述】:

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

【问题讨论】:

  • 您要复制还是移动?这些是不同的东西。
  • 根据 ::std::vector 包含的内容,还可以使用 ::std::memcpy::std::memmove
  • 或在 C++ 中 std::uninitialized_copy :)

标签: c++ c++11 containers


【解决方案1】:

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

【讨论】:

  • 这里 N 是 const 吗? array N 应该是常量。
  • @notbad 是的,N 是常量(我猜我应该使用问题中发布的n
  • 还有std::move。可悲的是,不是std::move_n
  • 如果大小 N 错误会怎样?即向量有 5 个元素,数组要复制 10 个? cpp 文档页面对此有点不清楚。
  • @Praetorian undefined... 所以,一些编译器可能会抛出异常,在其他地方它会覆盖一些内存?我希望它抛出异常,否则在越界时默默地破坏内存的原始数组有什么好处?
【解决方案2】:

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

here 就是活生生的例子。

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

here 是另一个活生生的例子。

【讨论】:

  • n 怎么样?不应该是std::copy(x.begin(), x.begin() + n, y.begin());吗?
  • 与其使用n这样的变量,使用x.size()不是更好吗?
  • 您可以使用x.size(),但它不会编译 - 这里的 N 是编译时常量,甚至是模板参数。 std::array 就像一个数组 - 它需要在编译时已知的大小。期间。
猜你喜欢
  • 2011-05-19
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多