Click here to Skip to main content
13,287,273 members (48,705 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


2 bookmarked
Posted 27 Jan 2012

The heck of vector of bool specialization

, 5 Feb 2012
Rate this:
Please Sign up or sign in to vote.
A glance around vector of bool-type
This is surely not a Tip/Trick, rather this is about understanding the peculiarity of vector<bool>, so that one can avoid certain pitfalls.

For the bool type, the vector container is specialized to store the Boolean values as bits rather than as values. This is done to achieve space optimization - instead of having 8 bits, it will use just 1 bit.

But this pre-determined optimization leads to few unwanted results.
  1. For example, this code won't compile.
    vector<bool> _vec;
    bool& b = _vec.front(); // This line is the culprit 

    But the same works fine if we have vector<short> or any other data type.

    This is because the functions like front(), back() return references and there are no pointers/references for bits (remember vector<bool> stores values as bits). The workaround is to use a special member called reference:

    vector<bool>::reference b = _vec.front();

    One way to solve this premature optimization is to provide our own allocator:

    vector<bool, NewAllocator> _vec

    or use vector<char> instead. But this requires un-necessary bool-char conversions.

  2. This special type has a special function flip() for reversing the bits - thus providing a different interface rather than following the interface of other related containers.

    Seeing all these, the trick is to avoid using vector<bool> totally - Anyway, it is deprecated and is going to be kicked out of the STL soon.

My reference:[^]

[I don't know if I can post this information in this section, but I just took a chance].

Thank you.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Lakamraju Raghuram
Software Developer
India India

Did my masters from IIT-M in Advanced Manufacturing Technology and working mainly on C++ in CAD domain from 2004 onwards.

You may also be interested in...

Comments and Discussions

QuestionWorks fine in VS2008 Pin
YoungCodeprojector29-Jul-12 4:28
memberYoungCodeprojector29-Jul-12 4:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 5 Feb 2012
Article Copyright 2012 by Lakamraju Raghuram
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid