Click here to Skip to main content

The heck of vector of bool specialization

A glance around vector of bool-type
Sign Up to vote bad good
Add a reason or comment to your vote: x
Votes of 3 or less require a comment
See more: C++STL
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;
    _vec.push_back(true);
    _vec.push_back(false);
     
    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: http://www.gotw.ca/publications/N1211.pdf[^]
 
[I don't know if I can post this information in this section, but I just took a chance].
 
Thank you.
Posted 27 Jan '12
Edited 5 Feb '12


Alternative 1

This alternative posted by monclerinlight on 18:28 4 Feb '12 has been removed.

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

Your Filters
Interested
Ignored
     
  1. SAKryukov (583)
  2. CRDave1988 (390)
  3. CPallini (315)
  4. Varun Sareen (308)
  1. SAKryukov (13,971)
  2. OriginalGriff (8,238)
  3. Christian Graus (7,396)
  4. thatraja (5,300)
  5. Abhinav S (5,103)

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --

Advertise | Privacy | Mobile
Web04 | 2.5.120222.1 | Last Updated 5 Feb 2012
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid