问题
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