1

Let's say I have a struct using bit-fields like that :

struct SomeData
{
  char someChar:5;
  char someSmallerChar:3;
}

The size of the content of one SomeData should be one char long instead of two, thanks to bitfields.

Now if I want to organize my data this way...

class SomeDataContainer
{
  std::vector<char> someChar;
  std::vector<char> someSmallerChar;
}

... I lose the benefit I had with the bit-fields regarding space efficiency. The size of the equivalent container is now twice the original one.

Is there a way to create a vector of char:5 and char:3 or something similar to it to get the same benefits while having the data in this vector format (contiguous in memory) ?

19
  • std::vector<SomeData> doesn't fit your needs because continuity, right? Commented Jul 15, 2019 at 13:06
  • Yes, I need someChar's to be contiguous and std::vector<SomeData> would put someSmallerChar's in the middle. Commented Jul 15, 2019 at 13:07
  • 1
    Of course there is a way: you just have to implement your own container that implements this functionality. There's nothing like this in the standard C++ library, but you can always write your own, and if it complies sufficiently with C++ library's container requirements, it should be usable with the rest of the library (algorithms, etc...) Commented Jul 15, 2019 at 13:08
  • 1
    There is std::vector<bool> which has bit-level granularity (and std::bitset with a compile-time length). The next higher granularity provided by the standard library is std::vector<char> (or similar). You could write your own container that allows granularity at the level you need. Commented Jul 15, 2019 at 13:09
  • 1
    @max The std::vector<bool> disaster is solely because it is a specialization, and not a completely different container Commented Jul 15, 2019 at 13:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.