The main problem though is that vector<bool> behaves differently from any other data type. For instance, separate elements of the vector do not have unique addresses (because addresses are byte aligned).
This means that if you're doing anything with pointers on vectors, particularly if you're writing generic code (templates) then you very quickly run into cases where code is perfectly valid and correct for all types except for bool.
For instance, two adjacent elements in a vector are sizeof(T) apart in memory. Except when T=bool.
What's worse is that the spec says that all vector<T> must return a T& if you do an operator[] on them, but of course vector<bool> can't do this because there are no bools to reference, so the solution they came up with was to say that operator[] on vector<bool> returns a vector<bool>::reference which is an internal class that implicitly decays to bool.
This means that you can do `my_vec[0] = true;`, and you can do `bool b = my_vec[0];`, but if you do `auto b = my_vec[0];` then things go horribly wrong because the type of `b` is not `bool` but instead becomes `vector<bool>::reference`.
The main difficulty is that operator[] doesn't return a bool, but rather it returns some reference type that's convertible to a bool.
So if you do something like bool& begin = &vector[0]; bool& next = begin + 1;
That wouldn't work. I'm not even sure if that's a compilation error or if it just does the wrong thing. Vector<bool> is so cursed I do my best to never use it, but as a consequence I'm also not too familiar with it's details.
You can still use iterators though to iterate over the vector<bool>.
Yes. You can't have a normal bool pointer or reference into the vector, because there aren't any "regular" byte sized bools in there.
So any time you read a bool, it needs to create a new byte bool for the result. And when you write a bool, it needs to convert that bool to the correct bit flipping operation in the vector.
Particularly when you read a bool it's problematic because you can't e.g. take the address of it and expect to get an address inside the vector (which you can do with any other type of vector).
Tbf c++ does have a specific bool type (unlike c where it’s an int in disguise) - and if you want byte-aligned behaviour why not just use a vector<uint8_t> and bitshift/mask…also it’s the dynamically allocated version of a std::bitset so I think this actually makes sense as long as you know the quirks before making assumption…
The problem is, especially with multithreading, etc. you can get into issues if you try to use a vector<bool>. It would have made much more sense to have the vector<bool> work like anything else, and introduce a std::bitset or similar for this kind of behavior.
This is why I tend to just stick to C stdint types when I want specific data types while saving space. Consistent, configurable, and can be typedef-ed for clarity.
From a C perspective, since IDK C++: char is defined to be the smallest addressable unit (in other words, a machine byte, which may be more than 8 bits on cursed hardware). Since CHAR_MAX >= 127 per the ISO C standard, it's probably the best thing to use for a hacky boolean type (of course, when bool doesn't work). uint8_t could also be used, but I feel like it communicates that we need 8 bits specifically rather than "the minimal amount the machine can address individually."
Edit: Also, unsigned char might be my first instinct, but it doesn't particularly matter. Any non-zero value is truthy to C. So I'd probably use char since I'm a fan of brevity.
If you're actually using the elements as booleans, only zero/non-zero matters, so char, signed char, unsigned char (yeah these are actually 3 separate types lol cpp) are all the same in this context
Oh I read it incorrectly. I thought you asked what the bitset behavior was breaking.
Theoretically, it would break all code that try to handle it as a bitset by doing unsafe shitty read/write on the memory address. But also, it would be extremely easy to do a "replace all" of vector<bool> to bitset when upgrading the code.
But my question highlights a problem with vector<bool> - it can't work in generic code that expects vector to be contiguous, addressable with T*, and have a .data() function that gives you that. Because it doesn't.
It doesn't even support &bool_vec[0] or &*begin() - because neither return actual references, but a reference proxy class. You can't take the address of an rvalue class, so it fails to compile entirely.
It's very well defended, but on the flip side it's incompatible with a lot of generic contexts because it doesn't have the same API as vector<T> generally, only a subset of it. Some of which seems to exist solely for there to be a common subset (like the nested reference type alias).
And the worst part is it explicitly has a member function on its nested "reference" type - so currently it can't be left unspecialised by an implementation.
I'm not going to try defend the design of std::vector<bool> because it looks annoying to develop around, but this post got me wondering, so I Googled it. The underlying bit packing behavior and implementation is a remnant of C++98 with addons over years.
This design was set down before algoriths, iterators, ranges and during a time when concurrent programming was not the norm, if it existed at all.
I think this was mediocre idea that has aged like warm milk in a hot car. Not the terrible atrocious design people seem to make it out to be.
The bit packing behaviour can be genuinely useful as it saves memory and uses the cache more effectively. I have no problem with the implementation in and of itself.
The problem IMO is just that it is mapped to the vector<bool> type, while it behaves differently than any other vector in some cases, and its elements aren't really bools and don't act exactly the same. Even without concurrent programming. The "vector of bits" that vector<bool> actually is, is still very useful to have in the standard library, but would be better as a dedicated bitvector type. And vector<bool> should just act like any other vectors and just store a list of bools.
That is a reasonable complaint about it. I've only been programming with C++ for a few years. This is one of the many things that gets thrown around a lot in the cpp subreddits but rarely seems to get the context it deserves. I had to learn to frame the comments about performance costs in the same way. There are valid points to what's being said with these comments but there is often more context that much more experienced devs don't specify and it changes how newer developers like myself view things.
I legitimately tried to avoid using std::function and lambdas at one point early on because I read that they were "slow".
About performance costs there is indeed a lot of misinformation and misunderstanding about it on platform like Reddit. A lot of people seem to still think that more CPU cycles means slower, while CPU clock speed is rarely the bottleneck.
Also, it's perhaps a bit of a controversial opinion, but unless what you're doing is very performance critical, I think it's totally fine to use approaches that are not the most optimal but easier to use or that keep the code better organised. Development time often has much more strict limits than compute time, so I think that trades some performance to make it faster or easier to write the program is usually a good trade-off.
I agree about your maybe controversial opinion on development time and ergonomics being more critical than performance time. I am pushing myself to just get something written and working instead of fixating on whether it is the optimal decision or even a good way to do it.
I read once that there have been studies done in grocery stores where often times to much variety for a single item can reduce the overall sales figures for that item. People can't decide what bag of Lays they want and opt for not getting Lays at all rather than making a decision between one of twenty options. Things sometimes sell better when there are only a few of the most popular flavors because the impulse buy response can kick in.
In C++ there are a dozen ways to do most things and there are trade-offs for most of them. I think I've been struggling with that for a while and your opinion is one way I'm leaning into to pushing passed this observation. Picking what looks to be the most ergonomic option or even just the first option that comes to mind.
As far as performance goes. I was definitely affected by what is said on reddit. I'm a newer developer. I don't want to write buggy sluggish software. If people say that's slow I don't want to do it that way. It wasn't really until I followed a book for writing a terminal based text editor called Kilo earlier this year that I stopped bothering to consider that at all. When I saw how snappy and responsive that project stayed even with the number of memcopies and system calls being done to a heap allocated representation of a 1000k line text document with syntax highlighting every key stroke that I began to get a sense of just how powerful modern CPU's are and how little my struggling with the few hundred extra assembly instructions I'm agonizing over will ever matter in the project's I'm capable of producing.
Those concerns are probably valid for some and I like to think those that make those comments are often people working in high performance industries were their experience has colored there thought process. It is slow to them based on the way they view things and the criteria they've had to learn to evaluate against over years of experience in an industry where that matters. That doesn't mean I should assume it's slow based on what I need.
Yeah. I got my first multi core processor in 2004ish? The standard would have been written in the late 90's. Was concurrent programming something the average developer even considered?
My big problem with fork is that it requires you to build everything into the same process, then fork, and choose behavior depending on which of the instances you are. In many cases, you want multithreaded parallelism in the same process
In C++ a bool is actually 8 bits with the least or most significant bit set, depending on architecture. That's the smallest addressable unit available without extra bitwise operations.
That is what sizeof(bool) outputs. That 1 byte is based on the CHAR_BIT macro which the standard requires is atleast 8 bits. It could also be as much as 32 bits, apparently. Silly C++
That's the C remnant from a time, where a processor word was not guaranteed to be 8-bit (aligned). Also: CHAR_BIT is atleast 7 bit as a char is required to fit the ASCII table. The 8'th bit is already optional (but guaranteed on all modern systems with 8-bit aligned memory and 32/64 bit cpu words)
Okay, not valid because somewhere it's written that "this is undefined behaviour", but compilable, and it does what I wrote. Well, depending on which compiler you use, with some you get an output of 1, with others you get an output of 5. But that's kinda my point.
The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.
I guess that's not the ISO, but I'm not about to pull that out.
Quote from the book "From Mathematics to Generic Programming" by Alexander Stepanov (the creator of the stl) and Daniel Rose:
The name vector in STL was taken from the earlier programming languages Scheme and Common Lisp. Unfortunately, this was inconsistent with the much older meaning of the term in mathematics and violates Rule 3; this data structure should have been called array. Sadly, if you make a mistake and violate these principles, the result might stay around for a long time.
It's all use-case, I suppose. Larger programs can afford more refined solutions.
To say using uint8_t as a bool is bad because it can break when making templates is to say wood beams are bad because they will buckle under a skyscraper.
I'm not completely sure that in some cases there wouldn't be undefined behaviour, but even if it fails to compile the error will likely be horrible and not easily understandable.
Using uint_8 isn't bad, but rather it's not an option as a replacement if you're the one writing the templated code. Partually because you don't know that bool was actually the intent when you get given a uint_8, but more importantly because in every single function that templates on T and uses vector<T>, you have to write a distinct version of the function that special-cases vector<bool> in case your users instantiate the template with a bool, which should be very reasonable and users should want to do by default, because bools are a useful datatype.
I mean, as long as you know its a problem you can just use std::enable_if_t to block putting bools in your template. Or you can specialize your template to redirect bools to a more sensible type.
It's a fun landmine for those who don't know, though. But C++ is full of those.
Yes exactly. But if you're writing template code and don't know who's going to call it, you have to create specific carve-outs or overloads for vector<bool>, where if the designers had just let that be normal, you wouldn't need that special-case handling.
Bool is a byte. At minimum. All types are min 1 byte, by standard. And sizeof returns integers. Please stop arguing and just accept a common issue. Dont be a contrarian
A bool, by definition, in just about any language there is, always takes up the amount of space of the lowest addressable memory unit, which is 8 Bit (excluding some special, outdated architectures where you can access single bits directly). C++ is the only language I know of where a data type using bool uses single bits for storing them. Is it more efficient? Yes. But it breaks the universally accepted standard. Consistency is far more important than minimal efficiency improvements. Just add a seperate data type for when you really need that efficiency into the standard library.
I think the behavior of it is quite logical. Bits are supposed to be one bit in size. If you have them in isolation, they will have to expand to at least 8 bits, but once they are a vector, you give permission to the compiler to pack and optimize them. If you can't have them optimized, use a type that guarantees an individual address, if that is what you need
It depends a lot on what platform the software runs on. C++ runs on everything from 8-bit microcontrollers to high performance compute platforms. On a microcontroller there often is an instruction that modifies a bit in a single cycle, while it is more costly on other platforms
Yes and no. A bool variable is 8 bits, since by specification it needs its own address. But the information encoded in one bool is supposed to be one bit
The information encoded doesn't matter; within C++'s type system, a bool is not a bit. Meaning, vector<bool> does not actually hold any bools, and any code that attempts to interact generically with a vector that happens to be a vector<bool> may be subtly broken.
Threading is the most obvious culprit here. For any other element type it's safe for different threads to read and write to different elements of the vector. For vector<bool> it isn't, because its elements are always read and written to in groups of eight.
std::vector<bool> may be specialized to store bools compactly and non-contiguously. It is the only initialization of std::vector for which this is allowed, but it is not guaranteed by the standard.
No, the problem is that the standard allows it at all.
All other instantiations of std::vector are guaranteed to store addressable objects contiguously. std::vector<bool> is arbitrarily allowed to break this guarantee. This can break generic code if you don't defensively program around it, which defeats the whole point of having a strong type system with robust generic programming facilities.
What really should have happened is simply using the type system for its purpose. std::vector<bool> should not have been specialized, and a separate container named something like std::dynamic_bitset should have been introduced to cover the cases where you do want to store compacted boolean values. This way,std::vector maintains a consistent contract and the type system gets used to better express the programmer's intent.
The compiler is absolutely not allowed to pack contiguous bools. That breaks the addressability requirement of objects. If you want packed Boolean values, the language gives you plenty of ways to express that.
I'd rather have my bools packed, since I generally work with microcontrollers and need every byte I can save. For some reason, the compiler that comes with Arduino IDE tried to store my hundreds of bools bytewise and ran out of memory, and I had to make a struct to get them to pack the way I wanted. Also, packed bools can be set or unset together in a single operation, so it can be a lot faster.
If you are setting or reading a single bit, it is usually less performant because it requires more operations.
Also it can no longer be pointer iterated the same as any other vector could be, breaking templating code. You have to keep making special case code just for it.
And thats if you even know about it, since it's not clear just looking at the type that its completely different from every other specialization of its template.
Bitwise logic operations are supposed to be the fastest operations a CPU can run, though. Ideally you want to group up bits you're likely to read together into the same word so a single instruction reads all of them. Same goes for setting bits using a bitmask. You can still pointer iterate, but you're doing it per-word rather than per-bool. You'd get a speedup equal to the word size because you're effectively parallelizing your writes with a single bitwise logic instruction.
I personally tend to use C more than C++, and HDLs even more than that, but my first impression of bool was that it was meant to be a single bit in size so you could do things like that.
This seems like a special case that would benefit from its own type like bitset rather than having vectors arbitrarily work differently for a single type and break stuff unless you know to take care of it.
What's the problem with this? I've seen a lot of people so bitwise operator stuff as an optimization. What is wrong with being able to address the bits directly for any length?
It is the only vector type that doesn't return a mutable reference (among other things), so if you're using it in some core abstraction and later on someone wants to use that abstraction with bool types, that code either behaves incorrectly (potentially silently) or doesn't compile.
I ran into this exact scenario in my first job on the architecture team for a massive simulation. Working around it was incredibly annoying.
Edit: That is just my personal experience - the problem, in general, is that it breaks the API/contract/expectations of vector.
The full list (to my knowledge):
No pointers or contiguous layout
As part of the above, it is incompatible with std::span
No .data() function (????)
Broken range-based for loops (for(auto& b : vec)) doesn't compile
Not thread safe. If you have a (normal) vector where you assign a thread to each populated index, it is thread safe (single-owner). In vector<bool>, a single index shares its underlying data with other indices, so this breaks
I think you maybe missed my point. It's that building an abstraction with a foundation of vector that leaks some of its core contracts, like mutable reference based indexing and contiguous data type access, will end up breaking and biting you in unexpected ways. It's also that it breaks the (general) API contract of vector.
The question is more "why *wouldn't I* want this core, generic primitive to adhere to its API contract regardless of the type that I put into it?"
If you look at raw vector and ask "why do I want an array of bools", yea sure, whatever, use a literal array of bools or a bit set or this thing or that thing or who cares.
But as you start zooming out and building stuff around the *concepts* of vectors and arbitrary types, eventually you end up with, say, like, a Vehicle class, built on that abstraction. And then you go to build a vehicle that uses bools in a certain way, for business reasons, and suddenly your code doesn't compile. They didn't necessarily want a literal array of books - they just wanted to use your thing that says "you can use me with any generic type" except WOOPS not bools and only not-bools, for some reason.
I am specifically asking because i cannot recall ever using array of bools (in all of my used languages) over the 6+ years, except for my earliest years in my amateur code where i used array of bools + array of string (for example) vs array<struct=bool + str>
I gave examples in both of my comments for the real world use cases I encountered. Abstractions sitting at the basis of primitives that are used in a large (million+ LoC code base)
If you want a contrived explicit example of a literal array of bools, consider an array of coin flips, or any other data that can be thought of as a (ordered) sequence of truth or decision (yes/no) values.
The case I had at a previous job was we need to know if a retailer was available at a given time. We need to be able to check a lot of them very quickly. So we had a string of 1s and 0s, each one indicated a 15 minute segment of the week. That's too many bits to fit in an integer for a simple bitwise operator. I don't recall the implementation details anymore, but we the I/O for loading thousands of these strings for processing was kind of slow. It was PHP which didn't help.
We were on MySQL, this was during the lamp stack days. And I don't know if MySQL ever added features like that. I don't think it had native json support.
The problem is that it’s inconsistent and leads to unexpected bugs. If I want to use a bitmask because I really care about memory then I’ll use a bitmask
Try grabbing a pointer-to-bool from std::vector<bool> and see what happens.
Vector<bool> isn't that bad in a vacuum, honestly, since you can just avoid it. The real problem is when you write `template<typename T> class MyDataStruct { std::vector<T> innerStorage }` and then create a `MyDataStruct<bool>` and it unexpectedly falls apart. Now you have to build a pointless type trait system to remap bool onto uint8_t or something.
Problem of wrong implementation of bool, not for what use case for it. If you need separate implementation for it, then it should be excluded from start. Assume you have sequence of simple numbers and in that list got 12, 12 also number but wrong one. It’s same for std::vector<bool> differ from rest.
I don't know what this comment is trying to say. Dynamic bool collections with and without bit packing are both legitimate use cases, and of the two, vector<bool> should obviously be the latter because that is how vector already works. If you want a tightly packed collection that breaks vector's invariants, it should be its own type and not a specialization of vector.
I'm not sure what "wrong implementation of bool" is meant to mean either. A bool in C++ is not a single bit, definitionally.
Just when implement class need follow rules to all, not make 1 out of rest. Mem usage be good, but for it can be new one like memCompactVector<bool> etc.
Because std::vector<T> has interface all of its implementations must follow - stuff like iteration, dereference
And while storing booleans as bits in std::vector<bool> shrinks the space usage by nearly 90%, it also means it cannot fully implement the std:vector interface.
Good example is reference - in other vectors, you can take reference to one of its items. You can then use this reference to work with item directly.
auto vec = std::vector<int>();
vec.push_back(10);
// this will obtain reference to 0th item
auto& val = vec[0];
val = 15;
// this will print '15'
std::cout << vec[0] <<std::endl;
This is IMPOSSIBLE with std::vector<bool> because there are no bools inside to reference - and referencing bits is impossible as well.
Instead, it will return weird proxy object that is trying its best to pretend it is bool reference. But it cannot ddo everything - and that breaks interface
Its not that people don't see why the bit vector implementation can be useful, but its really not unreasonable to see "vector<bool>" and expect the type to be a vector and store bools (it does neither though)
Tbh at this point only solution for this problem would be disallowing it in linters and suggesting either deque or bitset depending of whether you want packing
Why would you want to bloat up your memory and waste 87% of your space? C++ fixed a mistake that the bool type introduced in C for simplicity of implementation. If you don't like vector bool for whatever reason then feel free to use vector uint8_t for the C style feeling
You bloat up the memory in other ways, since bits can only be accessed through bit shifting and boolean operations, and then need to be copied into an int8 anyway. Even if you just want to branch, the CPU will do bit arithmetic. There's specific reasons for when you want to store bools as bits, and not as bytes. VERY SPECIFIC reasons. Like accessing data that is already stored as packed bits, like a register. Or when you are absolutely sure you need to pack bits for dense computations (think: chess engine).
That's why everyone here agrees that it should have been a std::bit_vector class, while std::vector<bool> should have been one byte per bool. It's a landmine in various ways. For example, it breaks all basic assumptions you have about such a vector, like sizeof(T) * n being the total size of the vector in memory.
This kind of stuff is popular in the embedded world though. Working with processors with 8K of program memory and 128 bytes of RAM and some of those processors have single bit instructions. It's one of the reasons I have to delve into assembly.
Then you typically still lay a struct on top, and not an array.
But I know all about smart cards and densely packed formats, that's why I am mentioning "specific reasons". Chess engine is also a good example, 8x8 bits fit neatly into an uint64. Piece movement turns into bit shifts, checking legal moves is mostly AND and OR.
Otherwise, you're trading that 87% "dumb" memory for easily 5x the number of instructions, from a simple array lookup to bit arithmetic. "Small" isn't always good, especially on 64-bit architectures.
a[0] is no longer a bool&, instead a custom type pretending to be a bool& via operator overloading
can't a.data()
can't iterate via auto&& you can, but it suffers from the same issues as the aforementioned a[0] thing
access to disjoint indices is not necessarily thread-safe
iterator may not be a LegacyForwardIterator, preventing use of many standard iterator-taking functions (with an error at compile time, or at runtime, or UB if you try)
and it's not even guaranteed to use this optimisation
Vector<bool> taking 1 bit per element is sensible. What isn't is bool * only being precise to the byte (well it did make sense back in the 70s when memory was as fast as cpus but now the time required to perform a shift and mask is negligeable compared to the time saved from improving cache locality).
All objects in C++ must be addressable. Bits are not addressable, and therefore cannot constitute a full object.
And, being C++, you are given several ways to pack boolean values if you need to. You can do the classic bit flags yourself, or use a std::bitset, or you can use a bit field if you want to explicitly name your flags. So ultimately, I think that it's worth bool being a full byte just for consistency with all other data types, and anything sub-byte being an explicit opt-in.
I wish java had one single array type that is resizeable (takes literally 1 line of code in a gc language) rather than array, arraylist, tolist, aslist, listof, the list of list goes on listing
Python calls them "list", but also has only 1 type, which is what I think is the important part, not whether they are called "arrays". (and no, the arrays module doesn't count, that's a specialized library type, not comparable to the duality you have to deal with when using Java)
If your point is linked lists, lumping them with arrays is a mistake that breaks code in itself and linked lists are next to useless anyway. None of the lists i mentioned even is a linked list. They are all array types that are mutually incompatible for some bool reason.
It is not, no. My point is that the theoretical definition is different.
Arrays are defined as randomly-addressable blocks of data where each element is the same width. They're pretty low-level and not resizable generally (though some implementations allow that by making a copy.)
While lists retain some characteristics of arrays (like being ordered and allowing random access, though time complexity depends on the underlying implementation) but allow items to be added, removed, and reordered. You know, like a to-do list.
Lists are often wrappers around arrays, sure, which allows for fast random access at the cost of some operations (like add/remove/reorder) being costlier, while a linked list can do fast add/remove/reorder and sequential access while random access is more expensive, but at the end of the day, those are list operations, not array operations (even if some languages give arrays some of those capabilities.)
To throw in another one: bags don't preserve order and therefore don't support reordering but do support fast adding and removing. You know, like the items in a bag. That might be backed by an array too, but it's not an array or a list either. The contract is different.
Linked lists are super common and extremely useful. Just not as a list ADT.
As a List they're absolute trash, but there are so many linked lists that people don't think of as linked lists. Java's BufferedInputStream .flush() is textbook linked list traversal.
An array is packed in memory, resizing it naive way means allocating more memory at the tail. And who guarantees that there is free memory up there?
So, you either redefine array (lame), or copy it elsewhere on resize (expensive, but that's what various collections actually do under the hood), or just use another collection which doesn't require to be packed all in one place (at the cost of performance of iterating over it).
No list should sacrifice array compatibility for linked list compatibility ever. And then with java as i said the issue isnt just linked lists, but that there are multiple incompatible array based list types. And no, many of them don't allow resizing, if thats what you think is the essence of a list.
Yes, but the standard does not provide a size, deliberately to allow for implementation specific specializations like this.
If you need individually addressed bytes that can be zero or non zero, there are easy ways to do that, this is making a big deal over nothing (also the bit wise versions have actual uses)
EDIT: Also the standard type is using a bit to define boolean (0 or 1) it's just that the smallest addressable value is a byte, so they have to stuff it into a byte.
This has absolutely nothing to do with the standard not specifying a concrete size. What is stored in a vector<bool> is not bool, flat out. So its size is irrelevant.
Bitwise bool collections do indeed have legitimate use cases, which is why they should have been included in the standard as their own independent type. Including them as a goofy specialization of vector<bool> causes very real problems with template metaprogramming and thread safety.
759
u/Semper_5olus 10d ago
I see how it would be nice to have that option -- perhaps in another type analogous to long vs short ints -- but isn't a bit all you need?
175
u/ImpulsiveBloop 10d ago edited 10d ago
typedef uint8_t bool8;std::vector<bool8> booleansAsBytes;Or just use it directly
std::vector<uint8_t> fuckBools;66
u/gazorpazorpazorpazor 7d ago
"I wish this booleans required 8x more resources"
60
u/tickle-fickle 10d ago
That pisses me off so much, why not call it an std::bit_vector, why a different behavior for this one template type
143
u/geekosas 10d ago
Why waste 7 bits?
69
u/0xbenedikt 10d ago
I think the behavior of it is quite logical. Bits are supposed to be one bit in size. If you have them in isolation, they will have to expand to at least 8 bits, but once they are a vector, you give permission to the compiler to pack and optimize them. If you can't have them optimized, use a type that guarantees an individual address, if that is what you need
33
u/UnhappyJudge2487 10d ago
But bools as a standard are stored as bytes not bits. If you initiate a bool in cpp it's stored in a byte so it can be addressed
23
u/Immediate_Form7831 10d ago
Thank you for reminding me that C++ is an insane mess.
32
u/Luzzgar 10d ago edited 10d ago
Yet another example of C++ doing something in a weird and not obvious way.
Making a deep knowledge if its inner workings mandatory to use it correctly, which is the antithesis of a good programming language.
That's the kind of crucial details that should be communicated to the user directly.
12
u/TatharNuar 9d ago
I'd rather have my bools packed, since I generally work with microcontrollers and need every byte I can save. For some reason, the compiler that comes with Arduino IDE tried to store my hundreds of bools bytewise and ran out of memory, and I had to make a struct to get them to pack the way I wanted. Also, packed bools can be set or unset together in a single operation, so it can be a lot faster.
17
u/Mountain-Ox 10d ago
What's the problem with this? I've seen a lot of people so bitwise operator stuff as an optimization. What is wrong with being able to address the bits directly for any length?
3
u/jolharg 10d ago
just use flag bytes lol
2
u/Megane_Senpai 10d ago
Yeah, like data padding isn't a thing lol.
4
u/Buyer_North 10d ago
people just hating because they dont understand cpp...not gonna say why, because you dont deserve it if you dont know it
2
u/Sam260901 10d ago
For this to work u had to assume their wish servers store in c++
I'd have made first wish to change their language of storage of wishes to cpp, then on 2nd wish would've done this.
1
u/Banes_Addiction 10d ago
Sure. It totally seems like a worthwhile reason to make all pointers floating point.
1
u/stupled 10d ago
But is bool...
1
u/Successful-Active-21 10d ago
just wrap the bool and use vector<wrap<bool>>
1
u/Hot-Category2986 9d ago
*Internal screaming*
*Reread because maybe I misunderstood that*
Maybe I'm missing something about why someone would want to overcomplicate a bit...
1
u/QuietComputerDr 8d ago
I hope the genie also changed everyone's legacy code.
1
u/Infamous_Ticket9084 5d ago
Tbh at this point only solution for this problem would be disallowing it in linters and suggesting either deque or bitset depending of whether you want packing
1
u/MartinByde 5d ago
Wtf, why wouls you do that?
1
u/Ecstatic-Middle-9564 5d ago
vector<byte> or vector<uint8_t> C and C++ let you use pretty much anything as a boolean.
1
u/TerryHarris408 10d ago
Why would you want to bloat up your memory and waste 87% of your space? C++ fixed a mistake that the bool type introduced in C for simplicity of implementation. If you don't like vector bool for whatever reason then feel free to use vector uint8_t for the C style feeling
0
u/yjlom 10d ago
Vector<bool> taking 1 bit per element is sensible. What isn't is bool * only being precise to the byte (well it did make sense back in the 70s when memory was as fast as cpus but now the time required to perform a shift and mask is negligeable compared to the time saved from improving cache locality).
-7
u/Kadabrium 10d ago
I wish java had one single array type that is resizeable (takes literally 1 line of code in a gc language) rather than array, arraylist, tolist, aslist, listof, the list of list goes on listing
0
u/NegZer0 10d ago
But bool is not a byte in C++ either, it’s implementation specific and sizeof(bool) is not required to be 1.
If you want a vector of bytes use vector<unsigned char>
0
u/StCreed 10d ago
Seems like people don't understand bits and boolean. If you don't understand it, just use a byte-vector.