Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising std::array from pointer into a buffer elegantly?

Tags:

c++

arrays

c++11

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.

like image 270
norlesh Avatar asked Oct 29 '25 09:10

norlesh


1 Answers

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.

like image 139
Dave S Avatar answered Oct 31 '25 00:10

Dave S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!