29 thg 10, 2010

C++ : Reference : STL Containers : bitset

bitset


class template
<bitset>
Bitset
A bitset is a special container class that is designed to store bits (elements with only two possible values: 0 or 1, true or false, ...).

The class is very similar to a regular array, but optimizing for space allocation: each element occupies only one bit (which is eight times less than the smallest elemental type in C++: char).

Each element (each bit) can be accessed individually: for example, for a given bitset named mybitset, the expression mybitset[3] accesses its fourth bit, just like a regular array accesses its elements.

Because no such small elemental type exists in most C++ environments, the individual elements are accessed as special references which mimic bool elements:

1
2
3
4
5
6
7
8
9
10
11
class bitset::reference {
  friend class bitset;
  reference();                                 // no public constructor
public:
  ~reference();
  operator bool () const;                      // convert to bool
  reference& operator= ( bool x );             // assign from bool
  reference& operator= ( const reference& x ); // assign from bit
  reference& flip();                           // flip bit value
  bool operator~() const;                      // return inverse value
}


Apart from overriding several operators and to provide direct access to the bits, bitsets have the feature of being able to be constructed from and converted to both integer values and binary strings (see constructor, bitset::to_ulong and bitset::to_string). They can also be directly inserted and extracted from streams in binary format.

Bitsets have a fixed size. For a similar container class that also optimizes for space allocation and allows for dynamic resizing, see the bool specialization of vector (vector<bool>).

In their implementation in the C++ Standard Template Library, bitsets take a single template parameter:
 
template < size_t N > class bitset;

Where the template parameter has the following meaning:
  • N: Number of bits to contain (size_t is an integral type).



Member functions



Bit access:


Bit operations:


Bitset operations:

Không có nhận xét nào:

Đăng nhận xét