Any guarantees with vector<bool> iterators?
cppreference says that the iterators for the
vector<bool> specialization are implementation defined and many not support traits like
ForwardIterator (and therefore
cplusplus adds a mysterious "most":
The pointer and iterator types used by the container are not necessarily neither pointers nor conforming iterators, although they shall simulate most of their expected behavior.
I don't have access to the official specification. Are there any iterator behaviors guaranteed for the
More concretely, how would one write standards-compliant code to insert an item in the middle of a
vector<bool>? The following works on several compilers that I tried:
std::vector<bool> v(4); int k = 2; v.insert(v.begin() + k, true);
Will it always?Автор: xan Источник Размещён: 08.11.2019 11:31
The fundamental problem with
vector<bool>'s iterators is that they are not ForwardIterators. C++14 [forward.iterators]/1 requires that ForwardIterators'
reference type be
const T&, as appropriate.
Any function which takes a forward iterator over a range of
Ts is allowed to do this:
T &t = *it; t = //Some value.
reference types are not
bool&; they're a proxy object that is convertible to and assignable from a
bool. They act like a
bool, but they are not a
bool. As such, this code is illegal:
bool &b = *it;
It would be attempting to get an lvalue reference to a temporary created from the proxy object. That's not allowed.
Therefore, you cannot use
vector<bool>'s iterators in any function that takes ForwardIterators or higher.
However, your code doesn't necessarily have to care about that. As long as you control what code you pass those
vector<bool> iterators to, and you don't do anything that violates how they behave, then you're fine.
As far as their interface is concerned, they act like RandomAccessIterators, except for when they don't (see above). So you can offset them with integers with constant time complexity and so forth.
vector<bool> is fine, so long as you don't treat it like a
vector that contains
bools. Your code will work because it uses
vector<bool>'s own interface, which it obviously accepts.
It would not work if you passed a pair of
vector<bool> iterators to
Автор: Pete Becker Размещён: 20.08.2016 03:59
Unless described below, all operations have the same requirements and semantics as the primary
vectortemplate, except that operations dealing with the
boolvalue type map to bit values in the container storage and
allocator_traits::construct(18.104.22.168) is not used to construct these values.