Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you call data() on a std::vector<bool>?

Tags:

c++

c++11

stl

C++11 has implemented data() member function on std::vector, which gives you a pointer to the memory array. Does this mean the template specialization std::vector<bool> have this member as well? Since this specialization doesn't store the data in terms of bool *, what kind of behavior can you expect from calling data() ?

like image 705
Narut Sereewattanawoot Avatar asked May 15 '13 15:05

Narut Sereewattanawoot


People also ask

What does vector data () do?

vector data() function in C++ STL The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements. Parameters: The function does not accept any parameters.

What is a bool vector?

The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocator for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.

Is std :: vector fast?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.


2 Answers

It won't compile, unless your implementation has a non-standard extension. The specialisation of std::vector<bool>, as specified in C++11 23.3.7/1, doesn't declare a data member.

like image 53
Mike Seymour Avatar answered Oct 07 '22 19:10

Mike Seymour


This page documenting the class explicitely indicates that the specialization does not provide this method.

The specialization has the same member functions as the unspecialized vector, except data, emplace, and emplace_back, that are not present in this specialization.

This other page as well as §23.3.7 of the C++ specifications do confirm it.

like image 26
didierc Avatar answered Oct 07 '22 18:10

didierc