bitset用法
bitset可以说是一个多位二进制数,每八位占用一个字节,因为支持基本的位运算,所以可用于状态压缩,n位bitset执行一次位运算的时间复杂度可视为n/32.
输出只能用cout
1.构造:
int a = 5;
string b = "1011";
char c[4] = {'1','0','1','0'};
bitset<10>s1(string("1001")); //0000001001
bitset<10>s2(int(8)); //0000001000
bitset<10>s3(8); //0000001000
bitset<4>s4(string("10001")); //1000
bitset<4>s5(int(32)); //0000
bitset<4>s6; //0000
bitset<4>s7(a); //0101
bitset<4>s8(b); //1011
bitset<4>s9(c); //1010
-
不够的位数自动补0
-
size小于附的值时,int取后几位,string取前几位
-
不进行赋初值时,默认全部为0
2.运算:
bitset<4>s1(string("1001"));
bitset<4>s2(string("1000"));
s1[1] = 1;
cout<<s1[0]<<endl; //1
cout<<s1<<endl; //1011
cout<<(s1==s2)<<endl; //0
cout<<(s1!=s2)<<endl; //1
cout<<(s1^s2)<<endl; //0011
cout<<(s1&s2)<<endl; //1000
cout<<(s1|s2)<<endl; //1011
cout<<(~s1)<<endl; //0100
cout<<(s1>>1)<<endl; //0101
3.函数:
bitset<4>s1(string("1001"));
bitset<4>s2(string("0011"));
cout<<s1.count()<<endl;//用于计算s1中1的个数
cout<<s1.size()<<endl;//s1的位数
cout<<s1.test(0)<<endl;//用于检查s1[0]是0or1并返回0or1
cout<<s1.any()<<endl;//检查s1中是否有1,并返回1or0
cout<<s1.all()<<endl;//检查s1中是否全部为1,并返回0or1
cout<<s1.none()<<endl;//检查s1中是否全不为1,并返回0or1
// flip
cout<<s1.flip(2)<<endl;//将参数位取反,0变1,1变0
cout<<s1.flip()<<endl;//不指定参数时,每一位取反
// set
cout<<s1.set()<<endl;//不指定参数时,每一位变为1
cout<<s1.set(3,1)<<endl;//指定两位参数时,将第一参数位的元素变为第二参数的值,第二参数位只能为0or1
cout<<s1.set(3)<<endl;//只有一个参数时,将参数下标处变为1
// reset
cout<<s1.reset(4)<<endl;//一个参数时将参数下标处变为0
cout<<s1.reset()<<endl;//不传参数时将bitset的每一位变为0
string s = s1.to_string(); //将bitset转换成string
unsigned long a = s1.to_ulong(); //将bitset转换成unsigned long
unsigned long long b = s1.to_ullong(); //将bitset转换成unsigned long long
标签:bitsets2,cout,bitsets1,int,用法,bitset,数据结构,string
From: https://www.cnblogs.com/marti88414/p/17617761.html