C++ bitset 及其應用?
bitset 是一種資料集,用於儲存多個布林值,但與可以儲存位序列的其他資料集(如布林陣列或布林向量)相比,它佔用的記憶體空間更少。
Bitset 以佔用的記憶體空間較少的格式儲存二進位制位,並以壓縮的形式儲存它們。訪問任一元素與其他元素相同,即透過使用其索引值,即 bitset_name[index]。但 bitset 中元素的索引是反向的。我們舉個例子,對於 bitset {01101001},第 0 個索引的元素為 1,依此類推。因此,0 位於索引 1、2、4、7。而 1 位於索引 0、3、5、6。
我們建立一個程式,其中將使用 bitset 的所有函式 -
示例
#include <bits/stdc++.h>
using namespace std;
#define setSize 32
int main() {
bitset<setSize> bset1; // value is 00000000000000000000000000000000
bitset<setSize> bset2(20); //value is 00000000000000000000000000010100
bitset<setSize> bset3(string("1100")); // value is 00000000000000000000000000001100
cout<<"The values of bitsets are :
" ;
cout<<"bitset 1 : "<<bset1<<endl;
cout<<"bitset 2 : "<<bset2<<endl;
cout<<"bitset 3 : "<<bset3<<endl;
cout << endl;
bitset<8> bset4; // value is 00000000
bset4[1] = 1;
cout<<"value after changing a bit :"<<bset4<<endl;
bset4[4] = bset4[1];
cout <<"changing value using other method :"<<bset4<<endl;
int numberofone = bset4.count();
int numberofzero = bset4.size() - numberofone;
cout<<"The set"<<bset4<<"has"<<numberofone<<"ones and"<<numberofzero<<"zeros
";
cout << "bool representation of " << bset4 << " : ";
for (int i = 0; i < bset4.size(); i++)
cout << bset4.test(i) << " ";
cout << endl;
if (!bset1.none())
cout << "bset1 has some bit set
";
cout <<".set() method sets all bits, bset4.set() = "<< bset4.set() << endl;
cout<<"changing a specific bit(4) to 0 "<<bset4.set(4, 0)<<endl;
cout<<"changing a specific bit(4) to 1 "<<bset4.set(4)<<endl;
cout<<"Resetting bit at position 2 :"<<bset4.reset(2)<<endl;
cout<<"Resetting bits of full bitset : "<<bset4.reset()<<endl;
cout<<"Flipping bit at position 2 : "<< bset4.flip(2) << endl;
cout<<"Flipping bit of array : "<<bset4.flip() << endl;
int num = 100;
cout << "
Decimal number: " << num << " Binary equivalent: " << bitset<8>(num);
return 0;
}輸出
The values of bitsets are : bitset 1 : 00000000000000000000000000000000 bitset 2 : 00000000000000000000000000010100 bitset 3 : 00000000000000000000000000001100 value after changing a bit :00000010 changing value using other method :00010010 The set00010010has2ones and6zeros bool representation of 00010010 : 0 1 0 0 1 0 0 0 .set() method sets all bits, bset4.set() = 11111111 changing a specific bit(4) to 0 11101111 changing a specific bit(4) to 1 11111111 Resetting bit at position 2 :11111011 Resetting bits of full bitset : 00000000 Flipping bit at position 2 : 00000100 Flipping bit of array : 11111011 Decimal number: 100 Binary equivalent: 01100100
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP