从C数组初始化std :: array的正确方法

bin*_*y01 6 c++ arrays algorithm copy initialization

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

I 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());
Run Code Online (Sandbox Code Playgroud)

还有这个

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);
Run Code Online (Sandbox Code Playgroud)

但这感觉相当笨重.有没有惯用的方法,这可能不涉及memcpy?对于MyClass`或许我最好使用构造函数获取一个std :: array进入成员但我无法弄清楚这样做的正确方法.?

Vla*_*cow 7

您可以使用std::copy标头中声明的算法<algorithm>.例如

#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() );
Run Code Online (Sandbox Code Playgroud)

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

std::copy( std::begin( f.kasme ), std::end( f.kasme ), a.begin() );
Run Code Online (Sandbox Code Playgroud)