bitset
A bitset is an array whose each value is either 0 or 1. For example, the following code creates a bitset that contains 10 elements:
bitset<10> s;s[1] = 1;s[3] = 1;s[4] = 1;s[7] = 1;cout << s[4] << "\n"; // 1cout << s[5] << "\n"; // 0
The benefit of using bitsets is that they require less memory than ordinary arrays, because each element in a bitset only uses one bit of memory. For example, if n bits are stored in an int array, 32n bits of memory will be used, but a corresponding bitset only requires n bits of memory. In addition, the values of a bitset can be efficiently manipulated using bit operators, which makes it possible to optimize algorithms using bit sets.(一个重要的优化工具)
bitset<10> s(string("0010011010")); // from right to leftcout << s[4] << "\n"; // 1cout << s[5] << "\n"; // 0bitset<10> s(string("0010011010"));cout << s.count() << "\n"; // 4bitset<10> a(string("0010110110"));bitset<10> b(string("1011011000"));cout << (a&b) << "\n"; // 0010010000cout << (a|b) << "\n"; // 1011111110cout << (a^b) << "\n"; // 1001101110
foo.size() 返回大小(位数)foo.count() 返回1的个数foo.any() 返回是否有1foo.none() 返回是否没有1foo.set() 全都变成1foo.set(p) 将第p + 1位变成1foo.set(p, x) 将第p + 1位变成xfoo.reset() 全都变成0foo.reset(p) 将第p + 1位变成0foo.flip() 全都取反foo.flip(p) 将第p + 1位取反foo.to_ulong() 返回它转换为unsigned long的结果,如果超出范围则报错foo.to_ullong() 返回它转换为unsigned long long的结果,如果超出范围则报错foo.to_string() 返回它转换为string的结果foo.test(0) test函数用来查下标处的元素是0还是1
std::bitset
https://www.cplusplus.com/reference/bitset/bitset/?kw=bitset
