【问题标题】:Proper way to initialize a std::array from a C array从 C 数组初始化 std::array 的正确方法
【发布时间】:2020-12-23 03:21:46
【问题描述】:

我从 C API 获取一个数组,我想将它复制到 std::array 以在我的 C++ 代码中进一步使用。那么这样做的正确方法是什么?

我2个用这个,一个是:

struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)

c_api_function(&f);
std::array<uint8_t, 32> a;
memcpy((void*)a.data(), f.kasme, a.size());

还有这个

class MyClass {
  std::array<uint8_t, 32> kasme;
  int type;
public:
  MyClass(int type_, uint8_t *kasme_) : type(type_)
  {
      memcpy((void*)kasme.data(), kasme_, kasme.size());
  }
  ...
}
...
MyClass k(kAlg1Type, f.kasme);

但这感觉相当笨重。有没有一种惯用的方法,可能不涉及 memcpy ?对于 MyClass`,也许我会更好 构造函数采用 std::array 移动到成员中,但我也无法弄清楚这样做的正确方法。 ?

【问题讨论】:

  • 为什么不std::copy
  • 除了尚未正式发布:auto x = std::to_array&lt;uint8_t, 32&gt;(cArrayPtr);

标签: c++ arrays algorithm initialization copy


【解决方案1】:

您可以使用在标头&lt;algorithm&gt; 中声明的算法std::copy。例如

#include <algorithm>
#include <array>

//... 

struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)

c_api_function(&f);
std::array<uint8_t, 32> a;
std::copy( f.kasme, f.kasme + a.size(), a.begin() );

如果f.kasme确实是一个数组那么你也可以写

std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() );

【讨论】:

  • @binary01 这是我的错误。:) 我删除了那部分帖子。:)
猜你喜欢
  • 2012-12-20
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
相关资源
最近更新 更多