我正在从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() );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句