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

Proper way to initialize a std::array from a C array

本文关键字:数组 方法 std 初始化      更新时间:2023-10-16

我正在从一个C API获取一个数组,我想将其复制到一个std::数组中,以便在我的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());

这个

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::数组,该数组被移动到成员中,但我也无法找到正确的方法?

您可以使用标头<algorithm>中声明的算法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() );