C++ – What data type should you use in C++ when working with binary data blocks

c

While string should be used for working with strings, I would like to know what structure you should use in C++ when working with blocks of data.

I'm asking this because it would be nicer to use one parameter instead of passing a char* data and size_t size (or a custom structure).

Best Answer

std::vector<unsigned char>

or, preferably,

std::vector<std::uint8_t>

(In C++11, uint8_t can be found in <cinttypes>. Older compilers, but not MSVC, may have the C99 header <inttypes.h>. If your data is a sequence of 16-bit units, use uint16_t etc.)

If the size of the data blocks is known at compile time, std::array is appropriate; it wastes less space than vector.