我从 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/