从C数组初始化std :: array的正确方法 [英] Proper way to initialize a std::array from a C array

查看:124
本文介绍了从C数组初始化std :: array的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting an array from a C API, and I'd like to copy this to a std::array for further use in my C++ code. So what is the proper way of doing that ?

我2用来做这件事,一个是:

I 2 uses for this, one is:

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并将其移入该成员,但我也无法找出执行此操作的正确方法.?

But this feels rather clunky. Is there an idiomatic way of doing this, that presumably doesn't involve memcpy ? For MyClass` perhaps I'm better off with the constructor taking a std::array that get moved into the member but I can't figure out the proper way of doing that either. ?

推荐答案

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

You can use algorithm std::copy declared in header <algorithm>. For example

#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 确实是一个数组,那么您也可以编写

If f.kasme is indeed an array then you can also write

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

这篇关于从C数组初始化std :: array的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆