从C数组初始化std::数组的正确方法
Proper way to initialize a std::array from a C array
我正在从一个C API获取一个数组,我想将其复制到一个std::数组中,以便在我的C++代码中进一步使用。那么,正确的方法是什么呢?
I 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::数组,该数组被移动到成员中,但我也无法找到正确的方法?
您可以使用标头<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() );
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- 复制几乎为空的数组的最快方法
- 通过JNI传递数据数组的最快方法是什么
- 在调用接收数组的方法时,模板化数组大小是不是一种糟糕的做法
- 数组元素打印的递归方法
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++数组队列实现方法错误
- 寻找一种更好的方法来表示无符号字符数组
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 创建异构顶点数据数组的可移植方法
- 打印字符数组地址的正确方法
- 还有其他方法可以在数组中写入多维数组吗?
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 指针数组方法的向量push_back编译但不运行
- 在函数内部使用数组方法
- 如何获取方法内部int数组(方法参数)的长度
- 如何在c++中访问向量类数组方法