The standard way to get a non-specialized container is std :: vector <bool>

Is there a standard way (or at least a semi-standard implemented in all popular compilers) to get a non-specific, not optimized, continuous container std::vector<bool> ?

I have a generic code related to std::vector which assumes they are all such standard, continuous containers. My current workaround is to use std::vector<int> , which simply stores 0 and 1, which I want in content, but it would be better to have the correct vector type.

+5
source share
2 answers

As a workaround, you can use a different type, char means. You can also write a wrapper around bool , something like:

 struct my_bool { operator bool() const { return b; } operator bool&() { return b; } bool b; }; 
+7
source

As a rule, using the specialization std::vector<bool> not considered good practice with exceptions to the course. Mostly because its interface is different than the primary std::vector<T> interface, and this causes a lot of confusion.

This irregularity is mentioned in several publications that are free on the Internet. Recent and IMHO good reading was written by Howard Hinnant, namely In vector<bool> .

In fact, there was once a proposal to remove it from the standard N1185 , but it was rejected for backward compatibility issues.

The most preferred alternative used as an alternative is to use std::vector<unsigned char> or std::vector<char> .

+1
source

Source: https://habr.com/ru/post/1276105/


All Articles