# STL中bitset的用法

bitset存储的是二进数位，就和一个bool性数组差不多。用法上和数组的操作方式也差不多。

# bitset定义

1     bitset<8> b;
2     bitset<8> bit(8);
3     bitset<8> tp1(string("01010101"));
4     bitset<8> tp2(bit);
5
6     cout << "  b = " << b << endl;
7     cout << "bit = " << bit << endl;
8     cout << "tp1 = " << tp1 << endl;
9     cout << "tp2 = " << tp2 << endl;

1   b = 00000000
2 bit = 00001000
3 tp1 = 01010101
4 tp2 = 00001000

# bitset的运算

 1     bitset<4> tp1(string("0101"));
2     bitset<4> tp2(string("1110"));
3
4     cout << "(tp1 & tp2) = " << (tp1 & tp2) << endl;
5     cout << "(tp1 | tp2) = " << (tp1 | tp2) << endl;
6     cout << "(tp1 ^ tp2) = " << (tp1 ^ tp2) << endl;
7     cout << "(~tp1) = " << (~tp1) << endl;
8
9     cout << "(tp1 &= tp2) = " << (tp1 &= tp2) << endl;
10     cout << "(tp1 |= tp2) = " << (tp1 |= tp2) << endl;
11     cout << "(tp1 ^= tp2) = " << (tp1 ^= tp2) << endl;
12
13     cout << "(tp1 <<= 1) = " << (tp1 <<= 1) << endl;
14     cout << "(tp1 ^= tp) = " << (tp1 ^= 4) << endl;
15
16     cout << "(tp1 == tp2) = " << (tp1 == tp2) << endl;
17     cout << "(tp1 != tp2) = " << (tp1 != tp2) << endl;

 1 (tp1 & tp2) = 0100
2 (tp1 | tp2) = 1111
3 (tp1 ^ tp2) = 1011
4 (~tp1) = 1010
5 (tp1 &= tp2) = 0100
6 (tp1 |= tp2) = 1110
7 (tp1 ^= tp2) = 0000
8 (tp1 <<= 1) = 0000
9 (tp1 ^= tp) = 0100
10 (tp1 == tp2) = 0
11 (tp1 != tp2) = 1

# bitset的函数

 1     bit.size();        //返回大小（长度）
2     bit.count();    //返回1的个数
3     bit.any();        //返回是否有1
4     bit.none();        //返回是否没有1
5     bit.set();        //全部置为1
6     bit.set(p);        //将p+1(下标从0开始!!)位置为1
7     bit.set(p,n);    //将p+1位置为n
8     bit.reset();    //全部置为0
9     bit.reset(p);    //将p+1位置为0
10     bit.flip();        //全部取反 等同于 (~bit)
11     bit.flip(p);    //将p+1位取反
12     bit.to_ulong();    //返回转换为 unsigned long  的结果，超范围会报错
13     bit.to_ullong();//返回转换为 unsigned long long 的结果，超范围报错
14     bit.to_string();//返回转换为 string 的结果

STL的容器基本讲的差不多了。熟练掌握STL好处我也就不多说了= = ，自己在做题的过程中慢慢琢磨熟练吧。

posted @ 2018-08-28 16:21  Xenny  阅读(...)  评论(... 编辑 收藏