A bit_vector is more like a vector < bool >

View versions (1)

Definition

Bit_vector is defined in the standard header <vector>, and in the nonstandard backward-compatibility header <bvector.h>.

Description

A bit_vector is like a vector<bool>. The difference between the two is that a vector requires at least one byte per element, but a bit_vector only requires one bit per element.

Short example of using bit_vector:

bit_vector V(5);
V[0] = true;
V[1] = false;
V[2] = false;
V[3] = true;
V[4] = false;

for (bit_vector::iterator i = V.begin(); i < V.end(); ++i)
  cout << (*i ? '1' : '0');
cout << endl;

If you need a container for a variable number of bits or Boolean values, you can use the class bit_vector, otherwise if you need a bitfield with static size, you should use http://codecogs.izyba.com/reference/computing/containers/bitset.php"bitset" .

Bit_vector Operations

OperationEffect
c.flip()Negates all Boolean elements (complement of all bits)
m[i].flip()Negates the Boolean element with index i (complement of a single bit)
m[i]=valAssigns val to the Boolean element with index i (assignment to a single bit)
m[i1] = m[i2]Assigns the value of the element with index i2 to the element with index i1

References

Example 1
Problem

This example of program illustrates examples of implicit casts done by the ostream class to a variable of bit_vector.

Workings
#include <vector>
#include <iostream>

using namespace std;

int main( )
{
   bit_vector v; 

   v.push_back(false);
   bit_vector::reference ref1=v.at(0);
   cout <<ref1<<endl; // ref1 implicitly cast to bool 

   bool b1; 

   // one form of an explicit cast
   b1=ref1.operator bool( );
   cout <<b1<<endl; 

   // another form of an explicit cast
   b1=bool(ref1);
   cout <<b1<<endl;

   return 0;
}
Solution

Output:

0
0
0

References