Why is vector not an STL container
- 2020-06-19 11:10:19
- OfStack
preface
The reason is that yesterday, when I was looking up range base for loop related things, I saw vector < bool > It's an proxy iterator, which is very special, so I studied it curiously.
First vector
<
bool
>
It's not an vector container in the usual sense, it's a legacy issue.
As early as C++98, there was vector
<
bool
>
This is the type, but vector was used to save space
<
bool
>
It's not stored in 1 Byte1 Byte, it's stored in 1 bit1 bit!
With operator[], the normal container would return a reference to the corresponding element, but not to vector
<
bool
>
In fact, one "proxy reference" is visited instead of one "true reference", and the return is "std::vector"
<
bool
>
: object of type reference.
And in the 1 general case
vector<bool> c{ false, true, false, true, false };
bool b = c[0];
auto d = c[0];
The initialization of b implies an implicit cast. For d, the type is not bool, but 1 vector
<
bool
>
Is an inner class.
If you change the value of d, the value of c will also change
d = true;
for(auto i:c)
cout<<i<<" ";
cout<<endl;
// The above formula will output 1 1 0 1 0
If c is destroyed, d becomes a dangling pointer, and operations on d are undefined.
So it doesn't satisfy the basic operations of container 1, such as address to pointer initialization [because there's no way to address a single 11 bit, or make references]
vector<bool> c{ false, true, false, true, false };
bool &tmp = c[0]; // Error, cannot compile, for reference, because c[0] not 1 An lvalue
bool *p = &c[0]; // Error, unable to compile because cannot be combined 1 A temporary quantity address is bound to a pointer
So why vector < bool > Either a standard container, or because it does not support some of the basic operations that a container should have.
What is the correct way of using C++11's range-based for?
Clause 6: When auto deduces unexpected types, it initializes the semantics with explicit types
conclusion