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

冷暖自知 提交于 2021-02-16 16:14:29

问题


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 ?

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());

And this

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);

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. ?


回答1:


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() );

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

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


来源:https://stackoverflow.com/questions/33444344/proper-way-to-initialize-a-stdarray-from-a-c-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!