C ++ Primer study note _ 14 _ Standard Template Library _ bitset bit collection container, _ 14_bitset
C ++ Primer study note _ 14 _ Standard Template Library _ bitset bit set container
The bitset container is a sequence container of bit elements. Each element occupies only one bit and has a value of 0 or 1, which saves a lot of memory space. Is the storage of a bitset. Its 10 elements only use two bytes of space.
To use bitset, You need to declare the header file "# include <bitset>"
1. Create a bitset object
When creating a bitset object, you must specify the container size. Once defined, the size of a bitset object cannot be modified. The following statement defines the bitset object B, which can contain 100 elements, that is, 100 bits. At this time, the values of all elements are 0.
Bitset <100> B
2. Set element values
(1) subscripts
#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;}
Running result:
1001000010
(2) set the element to 1 at a time using the set () method.
#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;}
Running 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;}
Running 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;}
Running result:
1111011110
3. Output Elements
(1) use subscript to output elements
Such as the above Code
(2) directly output all elements 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;}
Running result:
1111011110
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.