What is the 'proper' way in C++11 and beyond to initialise a std::array from a pointer into a buffer?
I currently have
using guid_t = std::array<uint8_t, 16>;
inline guid_t make_guid(const uint8_t * bytes)
{
    guid_t res;
    for (int i = 0; i < res.size(); i++)
    {
        res[i] = bytes[i];
    }
    return res;
}
in my code but this just appears sloppy and inefficient - it seems like this should be a one liner using something in the standard libraries however I can't find it anywhere via searching.
There are a handful of options, assuming that bytes always have at least size valid elements.
std::copy_n(bytes, res.size(), res.begin());
or
std::copy(bytes, bytes+res.size(), res.begin());
You could also use std::memcpy, but I prefer the above two, as they work with non-byte data as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With