Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard way of getting a non-specialized std::vector<bool> container

Tags:

c++

c++17

vector

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

I have some generic code dealing with std::vectors which assumes they are all such standard, contiguous containers. My current workaround is to use a std::vector<int> which just stores 0's and 1's, which is what I want content-wise, but it would be nicer to have the correct vector type.

like image 203
Danra Avatar asked Mar 27 '18 09:03

Danra


People also ask

What is wrong with STD vector bool?

First, what's wrong with vector<bool> ? Because vector<bool> holds bits instead of bools, it can't return a bool& from its indexing operator or iterator dereference. This can play havoc on quite innocent looking generic code.

What is vector bool in c++?

The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocatorallocatorAllocators are used by the C++ Standard Library to handle the allocation and deallocation of elements stored in containers. All C++ Standard Library containers except std::array have a template parameter of type allocator<Type> , where Type represents the type of the container element.https://learn.microsoft.com › cpp › standard-library › allocatorsAllocators - Microsoft Learn for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.

How do you create a Boolean vector?

Element i of the vector created by vector1 == vector2 equals TRUE if vector1[i] == vector2[i] and equals FALSE otherwise. A vector in which every element is TRUE or FALSE is called a Boolean vector.


2 Answers

As workaround you might use other type, char comes in mind. Else you can write a wrapper around bool, something like:

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

    bool b;
};
like image 184
Jarod42 Avatar answered Oct 11 '22 02:10

Jarod42


Generally, use of std::vector<bool> specialization is not consider a good practice, with exceptions of-course. Mainly, because its interface is different with that of the primary std::vector<T> and this causes a lot of confusion.

This irregularity, is mentioned in several publications that are loose in the web. A recent one and IMHO a good read is written by Howard Hinnant namely On vector<bool>.

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

Most proposed semi-standard alternative is the use of std::vector<unsigned char> or std::vector<char>.

like image 30
101010 Avatar answered Oct 11 '22 03:10

101010