C + + Primer learning Note _14_ Standard Template Library _bitset bit collection container
The Bitset container is a bit-bit element of the sequence container, each element occupies only one bit bit, the value is 0 or 1, thus saving memory space. is a Bitset store that uses only two bytes of space for its 10 elements.
Use Bitset to declare header file "#include <bitset>"
1. Create a Bitset object
When you create a Bitset object, you must specify the size of the container. Once the size of the Bitset object is defined, it cannot be modified. The following statement defines the Bitset object B, which can hold 100 elements, or 100 bits, at which point the value of all elements is 0.
Bitset<100> b
2. Set the element value
(1) Using subscript method
#include <bitset> #include <iostream>using namespace Std;int main () { bitset<10> B; B[1] = 1; B[6] = 1; B[9] = 1; for (int i = B.size ()-1; I >= 0; i--) cout << b[i]; cout << Endl; return 0;}
Operation Result:
1001000010
(2) using the Set () method, set the element to 1 at once
#include <bitset> #include <iostream>using namespace Std;int main () { bitset<10> B; B.set (); for (int i = B.size ()-1; I >= 0; i--) cout << b[i]; cout << Endl; return 0;}
Operation Result:
1111111111
(3) Set a pos bit to 1 using the Set (POS) method
#include <bitset> #include <iostream>using namespace Std;int main () { bitset<10> B; B.set (1, 1); B.set (6, 0); B.set (9, 1); for (int i = B.size ()-1; I >= 0; i--) { cout << b[i]; } cout << Endl; return 0;}
Operation Result:
1000000010
(4) Use the Reset (POS) method to set a pos bit to 0
#include <bitset> #include <iostream>using namespace Std;int main () { bitset<10> B; B.set (); B.reset (0); B.reset (5); for (int i = B.size ()-1; I >= 0; i--) { cout << b[i]; } cout << Endl; return 0;}
Operation Result:
1111011110
3. Output element
(1) Using subscript method to output the element
As the above code
(2) Output all elements directly to the output stream
#include <bitset> #include <iostream>using namespace Std;int main () { bitset<10> B; B.set (); B.reset (0); B.reset (5); cout << b << Endl; return 0;}
Operation Result:
1111011110
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + Primer learning Note _14_ Standard Template Library _bitset bit collection container