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 constructorbitset::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:


bitset::bitset


public member function
bitset ( );

bitset ( unsigned long val );

template<class charT, class traits, class Allocator>
explicit bitset ( const basic_string<charT,traits,Allocator>& str,
   typename basic_string<charT,traits,Allocator>::size_type pos = 0,
   typename basic_string<charT,traits,Allocator>::size_type n =
      basic_string<charT,traits,Allocator>::npos);
Construct bitset
Constructs a bitset container object.
If the default constructor is used, the bitset is initialized with zeros, otherwise its initial content depends on the parameters used:

Bitsets have a fixed size, which is determined by their class's template parameter:
template <size_t N> class bitset;


Where N is the size, specified as an integer value of type size_t.

Parameters

val
Integral value whose bits are copied to the bitset elements, up to the smaller of the bitset size and the size in bits of an unsigned long.
str
String containing a binary value (zeros and ones). These are parsed and used to initizialize the bits. If some character other than zero or one is found, the function throws an invalid_argument exception.
pos
First character in the string to be read as the content for the bitset.
n
Number of characters to read. A value of string::npos specifies that as many characters as possible are to be read.


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// constructing bitsets
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<10> first;                   // empty bitset

  bitset<10> second (120ul);          // initialize from unsigned long

  bitset<10> third (string("01011")); // initialize from string

  return 0;
}


The code does not produce any output, but demonstrates some ways in which a bitset container can be constructed.



bitset operators


functions
** bitset member functions: ***
bitset<N>& operator&= (const bitset<N>& rhs);
bitset<N>& operator|= (const bitset<N>& rhs);
bitset<N>& operator^= (const bitset<N>& rhs);
bitset<N>& operator<<= (const bitset<N>& rhs);
bitset<N>& operator>>= (const bitset<N>& rhs);
bitset<N> operator~() const;
bitset<N> operator<<(size_t pos) const;
bitset<N> operator>>(size_t pos) const;
bool operator== (const bitset<N>& rhs) const;
bool operator!= (const bitset<N>& rhs) const;

*** global functions: ***
template<size_t N>
  bitset<N> operator& (const bitset<N>& lhs, const bitset<N>& rhs);
template<size_t N>
  bitset<N> operator| (const bitset<N>& lhs, const bitset<N>& rhs);
template<size_t N>
  bitset<N> operator^ (const bitset<N>& lhs, const bitset<N>& rhs);

*** iostream global functions (extraction/insertion): ***
template<class charT, class traits, size_t N>
  basic_istream<charT, traits>&
    operator>> (basic_istream<charT,traits>& is, bitset<N>& rhs);
template<class charT, class traits, size_t N>
  basic_ostream<charT, traits>&
    operator<< (basic_ostream<charT,traits>& os, bitset<N>& rhs);
Bitset operators
Bitset containers support a different set of operators than the other container classes, mainly to support bitwise operators and to allow them to be insert/extracted directly to/from streams.

All these operators emulate for the bitset container the bitwise logic which applies to fundamental data types.

Parameters

lhs
Left-hand side bitset object (global functions). It must be of the same amount of bits as the right-hand side bitset object (i.e. with the same N template parameter).
rhs
Right-hand side bitset object. For member functions, rhs must have the same amount of bits as the bitset object.
is,os
istream or ostream object from which a bitset object is respectively extracted or inserted. The format in which bitsets are inserted/extracted is binary (successions of 0's and 1's).


Return value

Member functions: either *this or the result of the comparison.
Global functions: The left-hand side object (lhsis or os).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// bitset operators
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> first (string("1001"));
  bitset<4> second (string("0011"));

  cout << (first^=second) << endl;          // 1010 (XOR,assign)
  cout << (first&=second) << endl;          // 0010 (AND,assign)
  cout << (first|=second) << endl;          // 1011 (OR,assign)

  cout << (first<<=2) << endl;              // 1100 (SHL,assign)
  cout << (first>>=1) << endl;              // 0110 (SHR,assign)

  cout << (~second) << endl;                // 1100 (NOT)
  cout << (second<<1) << endl;              // 0110 (SHL)
  cout << (second>>1) << endl;              // 0001 (SHR)

  cout << (first==second) << endl;          // false (0110==0011)
  cout << (first!=second) << endl;          // true  (0110!=0011)

  cout << (first&second) << endl;           // 0010
  cout << (first|second) << endl;           // 0111
  cout << (first^second) << endl;           // 0101

  return 0;
}




bitset::bitset


public member function
bitset ( );

bitset ( unsigned long val );

template<class charT, class traits, class Allocator>
explicit bitset ( const basic_string<charT,traits,Allocator>& str,
   typename basic_string<charT,traits,Allocator>::size_type pos = 0,
   typename basic_string<charT,traits,Allocator>::size_type n =
      basic_string<charT,traits,Allocator>::npos);
Construct bitset
Constructs a bitset container object.
If the default constructor is used, the bitset is initialized with zeros, otherwise its initial content depends on the parameters used:

Bitsets have a fixed size, which is determined by their class's template parameter:
template <size_t N> class bitset;


Where N is the size, specified as an integer value of type size_t.

Parameters

val
Integral value whose bits are copied to the bitset elements, up to the smaller of the bitset size and the size in bits of an unsigned long.
str
String containing a binary value (zeros and ones). These are parsed and used to initizialize the bits. If some character other than zero or one is found, the function throws an invalid_argument exception.
pos
First character in the string to be read as the content for the bitset.
n
Number of characters to read. A value of string::npos specifies that as many characters as possible are to be read.


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// constructing bitsets
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<10> first;                   // empty bitset

  bitset<10> second (120ul);          // initialize from unsigned long

  bitset<10> third (string("01011")); // initialize from string

  return 0;
}


The code does not produce any output, but demonstrates some ways in which a bitset container can be constructed.

bitset::set


public member function
bitset<N>& set ( );
bitset<N>& set ( size_t pos, bool val = true );
Set bits
The version with no parameters sets (to 1) all the bits in the bitset.
The parameterized version, stores val as the new value for bit at position pos.

Parameters

pos
Order position of the bit whose value is modified. Order positions are counted from the rightmost bit, which is order position 0. size_t is an unsigned integral type.
val
Value to store in the bit (either true or false).


Return value

*this

If pos is not a valid bit position, out_of_range is thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::set
#include <iostream>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> mybits;

  cout << mybits.set() << endl;       // 1111
  cout << mybits.set(2,0) << endl;    // 1011
  cout << mybits.set(2) << endl;      // 1111

  return 0;
}

bitset::reset


public member function
bitset<N>& reset ( );
bitset<N>& reset ( size_t pos );
Reset bits
The version with no parameters resets all the bits in the bitset (sets al bits to 0).
The parameterized version, resets (sets to 0) the bit at position pos.

Parameters

pos
Order position of the bit whose value is modified. Order positions are counted from the rightmost bit, which is order position 0. size_t is an unsigned integral type.


Return value

*this

If pos is not a valid bit position, out_of_range is thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::reset
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> mybits (string("1011"));

  cout << mybits.reset(1) << endl;    // 1001
  cout << mybits.reset() << endl;    // 0000

  return 0;
}

bitset::flip


public member function
bitset<N>& flip ( );
bitset<N>& flip ( size_t pos );
Flip bits
The version with no parameters flips all the bits in the bitset, i.e. changes all 0s for 1s and all 1s for 0s.
The parameterized version, flips only the bit at position pos.

The unary operator~ performs the same operation as flip().

Parameters

pos
Order position of the bit whose value is flipped. Order positions are counted from the rightmost bit, which is order position 0. size_t is an unsigned integral type.


Return value

*this

If pos is not a valid bit position, out_of_range is thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::flip
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> mybits (string("0001"));

  cout << mybits.flip(2) << endl;     // 0101
  cout << mybits.flip() << endl;      // 1010

  return 0;
}

bitset::operator[]


public member function
bool operator[] ( size_t pos ) const;
reference operator[] ( size_t pos );
Access bit
The function returns the value (or a reference) to the bit at position pos.

With this operator, no range check is performed. Use bitset::test to read the value with bitset bounds checked.

Parameters

pos
Order position of the bit whose value is accessed. Order positions are counted from the rightmost bit, which is order position 0. size_t is an unsigned integral type.


Return value

*this

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// bitset::operator[]
#include <iostream>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> mybits;

  mybits[1]=1;             // 0010
  mybits[2]=mybits[1];     // 0110

  cout << "mybits: " << mybits << endl; 

  return 0;
}


bitset operators


functions
** bitset member functions: ***
bitset<N>& operator&= (const bitset<N>& rhs);
bitset<N>& operator|= (const bitset<N>& rhs);
bitset<N>& operator^= (const bitset<N>& rhs);
bitset<N>& operator<<= (const bitset<N>& rhs);
bitset<N>& operator>>= (const bitset<N>& rhs);
bitset<N> operator~() const;
bitset<N> operator<<(size_t pos) const;
bitset<N> operator>>(size_t pos) const;
bool operator== (const bitset<N>& rhs) const;
bool operator!= (const bitset<N>& rhs) const;

*** global functions: ***
template<size_t N>
  bitset<N> operator& (const bitset<N>& lhs, const bitset<N>& rhs);
template<size_t N>
  bitset<N> operator| (const bitset<N>& lhs, const bitset<N>& rhs);
template<size_t N>
  bitset<N> operator^ (const bitset<N>& lhs, const bitset<N>& rhs);

*** iostream global functions (extraction/insertion): ***
template<class charT, class traits, size_t N>
  basic_istream<charT, traits>&
    operator>> (basic_istream<charT,traits>& is, bitset<N>& rhs);
template<class charT, class traits, size_t N>
  basic_ostream<charT, traits>&
    operator<< (basic_ostream<charT,traits>& os, bitset<N>& rhs);
Bitset operators
Bitset containers support a different set of operators than the other container classes, mainly to support bitwise operators and to allow them to be insert/extracted directly to/from streams.

All these operators emulate for the bitset container the bitwise logic which applies to fundamental data types.

Parameters

lhs
Left-hand side bitset object (global functions). It must be of the same amount of bits as the right-hand side bitset object (i.e. with the same N template parameter).
rhs
Right-hand side bitset object. For member functions, rhs must have the same amount of bits as the bitset object.
is,os
istream or ostream object from which a bitset object is respectively extracted or inserted. The format in which bitsets are inserted/extracted is binary (successions of 0's and 1's).


Return value

Member functions: either *this or the result of the comparison.
Global functions: The left-hand side object (lhsis or os).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// bitset operators
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> first (string("1001"));
  bitset<4> second (string("0011"));

  cout << (first^=second) << endl;          // 1010 (XOR,assign)
  cout << (first&=second) << endl;          // 0010 (AND,assign)
  cout << (first|=second) << endl;          // 1011 (OR,assign)

  cout << (first<<=2) << endl;              // 1100 (SHL,assign)
  cout << (first>>=1) << endl;              // 0110 (SHR,assign)

  cout << (~second) << endl;                // 1100 (NOT)
  cout << (second<<1) << endl;              // 0110 (SHL)
  cout << (second>>1) << endl;              // 0001 (SHR)

  cout << (first==second) << endl;          // false (0110==0011)
  cout << (first!=second) << endl;          // true  (0110!=0011)

  cout << (first&second) << endl;           // 0010
  cout << (first|second) << endl;           // 0111
  cout << (first^second) << endl;           // 0101

  return 0;
}

bitset::to_ulong


public member function
unsigned long to_ulong ( ) const;
Convert to unsigned long integer
Returns an unsigned long with the integer value that has the same bits set as the bitset.

Parameters

none

Return value

Integer value with the same bits set as the bitset.

If the bitset is too long to be represented as an unsigned long, an overflow_error exception is thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::to_ulong
#include <iostream>
#include <bitset>
using namespace std;

int main ()
{
  bitset<4> mybits;     // mybits: 0000

  mybits.set();         // mybits: 1111

  cout << mybits << " as an integer is: " << mybits.to_ulong() << endl;

  return 0;
}


Output:
1111 as an integer is: 15


bitset::to_string


public member function
template <class charT, class traits, class Allocator>
  basic_string<charT,traits,Allocator> to_string() const;
Convert to string
Constructs a basic_string object that represents the bitset as a succession of zeros and ones.

Notice that this function template uses the template parameters to define the return type. Therefore, they are not implicitly deduced by the compiler.

Parameters

none

Return value

String representing the bitset.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// bitset::to_string
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{

  string mystring;
  bitset<4> mybits;     // mybits: 0000

  mybits.set();         // mybits: 1111

  mystring=mybits.to_string<char,char_traits<char>,allocator<char> >();

  cout << "mystring: " << mystring << endl;

  return 0;
}


Output:
1111

bitset::count


public member function
size_t count ( );
Count bits set
Returns the amount of bits in the bitset that are set (i.e., have a value of 1).

Parameters

none

Return value

The number of bits set.

size_t is an unsigned integral type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::count
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<8> myset (string("10110011"));

  cout << "myset has " << int(myset.count()) << " ones ";
  cout << "and " << int(myset.size()-myset.count()) << " zeros.\n";

  return 0;
}


Output:
myset has 5 ones, and 3 zeros.

bitset::size


public member function
size_t size() const;
Return size
Returns the number of bits in the bitset.

Parameters

none

Return Value

The number of bits in the bitset. This is the template parameter N.

size_t is an unsigned integral type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bitset::size
#include <iostream>
#include <bitset>
using namespace std;

int main ()
{
  bitset<8> first;
  bitset<4> second;

  cout << "first.size() is " << (int) first.size() << endl;
  cout << "second.size() is " << (int) second.size() << endl;

  return 0;
}


Output:
first.size() is 8
second.size() is 4

bitset::any


public member function
bool any ( ) const;
Test if any bit is set
Returns whether any of the bits in the bitset is set.

Parameters

none

Return value

true if any of the bits in the bitset is set, and false otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// bitset::any
#include <iostream>
#include <bitset>
using namespace std;

int main ()
{
  bitset<16> mybits;

  cout << "enter a binary number: ";
  cin >> mybits;

  if (mybits.any())
    cout << "mybits has " << (int)mybits.count() << " bits set.\n";
  else cout << "mybits has no bits set.\n";

  return 0;
}

bitset::none


public member function
bool none ( ) const;
Test if no bit is set
Returns whether none of the bits in the bitset are set.

Parameters

none

Return value

true if none of the bits in the bitset are set, and false otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// bitset::none
#include <iostream>
#include <bitset>
using namespace std;

int main ()
{
  bitset<16> mybits;

  cout << "enter a binary number: ";
  cin >> mybits;

  if (mybits.none())
    cout << "mybits has no bits set.\n";
  else
    cout << "mybits has " << (int)mybits.count() << " bits set.\n";

  return 0;
}

bitset::test


public member function
bool test ( size_t pos ) const;
Return bit value
Returns whether bit at position pos in the bitset is set.

Unlike access operator ([]), this function perform a range check on pos before retrieveing the bit value.

Parameters

pos
Order position of the bit whose value is flipped. Order positions are counted from the rightmost bit, which is order position 0. size_t is an unsigned integral type.


Return value

true if bit at position pos is set, and false otherwise.

If pos is not a valid bit position, out_of_range is thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// bitset::test
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

int main ()
{
  bitset<5> mybits (string("01011"));

  cout << "mybits contains:\n";
  cout << boolalpha;
  for (size_t i=0; i<mybits.size(); ++i)
    cout << mybits.test(i) << endl;

  return 0;
}


Output:
mybits contains:
true
true
false
true
false

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

Đăng nhận xét