从 C 数组初始化 std::array 的正确方法
Proper way to initialize a std::array from a C array
我从 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 移入成员中,但我也不知道这样做的正确方法。 ?
您可以使用 header <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() );
我从 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 移入成员中,但我也不知道这样做的正确方法。 ?
您可以使用 header <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() );