Reputation: 823
I have the following code:
#include <vector>
struct TestStruct {
std::vector<float> float_vect;
std::vector<bool> bool_vect;
};
void func(const TestStruct & test)
{
const float * p1 = test.float_vect.data(); //<--- this line works fine
const bool * p2 = test.bool_vect.data(); //<--- on this line error happens
}
int main()
{
TestStruct test;
func(test);
}
Error message:
passing 'const std::vector' as 'this' argument of 'void std::vector::data() [with _Alloc = std::allocator]' discards qualifiers [-fpermissive]
data()
method of std::vector
have const
specified.
Why this method works fine on float vector, and raises an error on boolean vector ?
Upvotes: 2
Views: 387
Reputation: 5191
std::vector<bool>
is a template specialization of the class std::vector<T>
in the STL. In order to use less memory, the boolean values are stored by 8 in a byte. It means there is no direct data accessible as you expect because the class doesn't store it in the same way than for other types.
Look at the doc :
The specialization has the same member functions as the unspecialized vector, except data, emplace, and emplace_back, that are not present in this specialization.
Upvotes: 1
Reputation: 4389
vector<bool>
is a specialization of a good old vector<T>
and it may be implemented differently from ordinary vector
(e.g. some space-saving optimizations may be employed). Side-effect of such design is that it does not always behave as ordinary vector
(many consider vector<bool>
to be broken because of that).
For example, the reference at http://en.cppreference.com/w/cpp/container/vector_bool does not mention vector<bool>::data()
at all. Therefore - you should not use it when using vector
with type bool
. The fact that you don't get an error similar to method not found
is - in your case - just a matter of how vector<bool>
is implemented by your compiler.
Upvotes: 3