0

# bitset簡介

(若是int或long long最多也就32位與64位，bitset可以超過64位)

## 一、引入函式庫

``````#include <bitset>
using namespace std;
``````

## 二、宣告

bitset的宣告方式如下:
(例如說宣告100個bit的bitset)

``````bitset<100> b;
``````

## 宣告的同時初始化

1. 直接以整數初始化
``````bitset<100> b = 1; //或bitset<100> b(1)
``````
1. 以長整數初始化
``````bitset<100> b(222UL);
``````
1. 以字串初始化
``````s = "100110101";
bitset<100> b(s);
``````

## 三、位元運算

1. AND 運算
``````b = b0 & b1;
``````
1. OR 運算
``````b = b0 | b1;
``````
1. XOR 運算
``````b = b0 ^ b1;
``````
1. index運算(從右往左數的位數)
``````b[0] = 1;
``````
1. 左移運算
``````b = b0 << 2;
``````
1. 右移運算
``````b = b0 >> 2;
``````
1. 每個位元反向
``````b = ~b0;
``````

## 四、輸入與輸出(cin, cout)

1. cin
``````bitset<8> b;
cin >> b; //假設輸入1010
cout << b << endl;
``````

`00001010`

1. cout
顯示 b 之內容，長度為 b.size()，
範例:
``````bitset<8> b(string("11011"));
cout << b << endl;
``````

`00011011`

# 應用: 子集合和問題

``````#include <iostream>
#include <vector>
#include <bitset>
using namespace std;

/*

bits是一個bit_vector，

*/
bool isSubsetSum(vector<int> &Set, int Sum)
{
bitset<1100> bits(1); //初始化bits = 1(bitset<>裡的數表示最多幾位數)
for (int num : Set)
{
bits |= bits << num;
}
return bits[Sum]; //檢查從右往左數的第Sum位是不是1
}

int main()
{
vector<int> arr = {2,2,3,5};
int target = 9; //測試arr裡面是否有子集和 = target
cout << (isSubsetSum(arr, target)?"YES":"NO") << endl;
}
``````