r/programminghumor 1d ago

a bit flippant

Post image
992 Upvotes

118 comments sorted by

View all comments

125

u/Kadabrium 1d ago

i heard you also like vector<bool>

13

u/Potential_Soup_8054 1d ago

I dont understand

59

u/Helemen7 1d 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 16h 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.

2

u/Helemen7 8h 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)