A std::vector
is guaranteed to be stored as one contiguous block of data(‡). Hence it is possible to treat a std::vector<unsigned char>
in basically the same way as an unsigned char
buffer. This means, you can memcpy
your data into the vector, provided you are sure it is large enough:
#include <vector>
#include <cstring>
#include <cstdint>
int main()
{
std::int32_t k = 1294323;
std::vector<unsigned char> charvec;
if (charvec.size() < sizeof(k))
charvec.resize(sizeof(k));
std::memcpy(charvec.data(), &k, sizeof(k));
return 0;
}
Note: The data()
function of std::vector
returns a void*
to the internal buffer of the vector. It is available in C++11 – in earlier versions it is possible to use the address of the first element of the vector, &charvec[0]
, instead.
Of course this is a very unusual way of using a std::vector
, and (due to the necessary resize()
) slightly dangerous. I trust you have good reasons for wanting to do it.
(‡) Or, as the Standard puts it:
(§23.3.6.1/1) [...] The elements of a vector are stored contiguously, meaning that if v
is a vector<T, Allocator>
where T
is some type other than bool
, then it obeys the identity
&v[n] == &v[0] + n for all 0 <= n < v.size().