STL_Bitset 女爷i 2022-09-23 04:52 149阅读 0赞 1.构造 <span style="font-family:Microsoft YaHei;font-size:24px;">std::bitset<16> foo;//构造16位的无参默认为0的位图 std::bitset<16> bar(0xfa2);//转化为二进制形式 std::bitset<16> baz(std::string("0101111001")); std::cout << "foo: " << foo << '\n'; std::cout << "bar: " << bar << '\n'; std::cout << "baz: " << baz << '\n';</span> ![Center][] bitset::operator\[\]: <span style="font-family:Microsoft YaHei;font-size:24px;">// bitset::operator[] #include <iostream> // std::cout #include <bitset> // std::bitset int main() { std::bitset<4> foo; foo[1] = 1; // 0010 foo[2] = foo[1]; // 0110 //operator[] 设置位图的具体位置的数字 std::cout << "foo: " << foo << '\n'; system("pause"); return 0; }</span> bitset::count() :计算已经被设置的个数(1的个数) <span style="font-family:Microsoft YaHei;font-size:24px;">// bitset::count #include <iostream> // std::cout #include <string> // std::string #include <bitset> // std::bitset int main() { std::bitset<8> foo(std::string("10110011")); std::cout << foo << " has "; std::cout << foo.count() << " ones and "; std::cout << (foo.size() - foo.count()) << " zeros.\n"; system("pause"); return 0; }</span> bitset::size(): 求出bitset的大小 bitset::test(): 可以判断某一位是否为1,若为1,返回true,若为0,返回false bitset::set():设置 <span style="font-family:Microsoft YaHei;font-size:24px;">// bitset::set #include <iostream> // std::cout #include <bitset> // std::bitset int main() { std::bitset<4> foo; std::cout << foo.set() << '\n'; //设置全为1 std::cout << foo.set(2, 0) << '\n'; //下标为2的设置为0 std::cout << foo.set(2) << '\n'; //设置下标2(从右开始数),默认为1 system("pause"); return 0; }</span> ![Center 1][] bitset::reset():设置为0 <span style="font-family:Microsoft YaHei;font-size:24px;">std::bitset<4> foo(std::string("1011")); //reset():设置为0 std::cout << foo.reset(1) << '\n';//原来是1,设置后变为0 std::cout << foo.reset() << '\n'; //全部变为0</span> bitset::flip(): <span style="font-family:Microsoft YaHei;font-size:24px;">// bitset::flip #include <iostream> // std::cout #include <string> // std::string #include <bitset> // std::bitset int main() { std::bitset<4> foo(std::string("0001")); std::cout << foo.flip(2) << '\n';// 0101 ,将下标为2的数字翻转为1 std::cout << foo.flip() << '\n';// 1010,将foo全部翻转 system("pause"); return 0; }</span> bitset::to\_string():变为string输出 [Center]: /images/20220721/a52f4b2c2f5f46119c7a50bf3ad75ecf.png [Center 1]: /images/20220721/b60ec9ae59f948498553437cb000efca.png
还没有评论,来说两句吧...