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

标签 c++ arrays algorithm initialization copy

我从 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在 header 中声明 <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() );

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

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

关于c++ - 从 C 数组初始化 std::array 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33444344/

相关文章:

c++ - 是否可以在没有 QApplication 的情况下使用 QML 和 QtQuick?

c++ - 来自现有 std::array 的 std::initializer 列表,无需枚举每个元素

javascript - 如何使用循环创建动态对象键/值?

java - 如何从java中的json文件中获取value中的特定值?

Python 树递归

algorithm - 递归和动态规划

c++ - 将 shared_ptr 传递给函数 - 需要说明

c++ - 在没有事件 Hook 的情况下通信应用程序

C++ - 将二进制文件的一部分读入位集

c# - 价格根据datetime中的天数递增和递减