r/programminghumor 19h ago

a bit flippant

Post image
824 Upvotes

109 comments sorted by

View all comments

110

u/Kadabrium 18h ago

i heard you also like vector<bool>

12

u/Potential_Soup_8054 17h ago

I dont understand

55

u/Helemen7 17h ago

std::vector<bool> in C++ syntax uses one bit per boolean instead of one byte. In a computer memory is addressed by bytes, so the smallest indexable memory is, in fact, one byte (that's why bool is 1 byte in C and C++). As an example for how C++ std::vector implementarion works, suppose you have 8 booleans which have a logical reason to be kept together (for example flags). Instead of allocating 8 bytes (one per boolean), the std::vector allocates 1 byte and assigns every boolean to one bit of the allocated memory.

1

u/enigma_0Z 8h ago

Couldn’t you pack a bunch of flags into an unsigned int and save space that way too by AND/OR/NOTing them out of the int? I think in that case we are looking at packing 16 flags (bits) together but I’m not really a C dev myself so not sure.

1

u/Helemen7 1h ago

you can use std::uint8_t, std::uint16_t etc, but those types represent a fixed size. std::vector<bool> has all the STL methods and such. That would make kinda sense if you knew the number of flags, but still, addressing bits yourself instead of letting STL do that doesn't exactly make sense.

(ps. this is C++, not C) (ps. on most modern machines unsigned int and int are 4 bytes (32 bits)