intro:
在Utilities library下,头文件<bitset>内;
The class template
bitset
represents a fixed-size sequence ofN
bits. Bitsets can be manipulated by standard logic operators and converted to and from strings and integers. For the purpose of the string representation and of naming directions for shift operations, the sequence is thought of as having its lowest indexed elements at the right, as in the binary representation of integers.
bitset
meets the requirements of CopyConstructible and CopyAssignable.
注意:数字的bitset不等于内存中的二进制补码的反码,因为在c++中,数字以小端序在内存中储存,而bitset使用的是大端序。
construct
//1
std::bitset<16> bin1;
//2
unsigned long long t=1145141919810;
std::bitset<16> bin2(t);
//3
std::string s3="dfdfddff";
std::bitset<16> bin3(s3,0,std::string::npos,'d','f');
//5
std::bitset<8> bin5("XXXXYYYY", 8, 'X', 'Y'); // [0,0,0,0,1,1,1,1]
std::cout<<std::format("{}\n{}\n{}\n{}\n",bin1.to_string(),bin2.to_string(),bin3.to_string(),bin5.to_string());
注意:(4)的std::string_view 与std::string有默认转换运算符,无需担心转换问题,貌似“”内容是当作Char*来解释的
Element access
//element access
std::cout<<bin2[11]<<'\n'<<bin2.test(11)<<'\n';
if (bin2.any()){
std::cout<<"any\n";
}
std::cout<<bin2.count()<<'\n';
Capacity
//capacity
std::cout<<bin2.size()<<'\n';
Modifiers
//modifiers
bin2^=1;
bin2<<=15;
bin2.set(0);
bin2.reset(1);
bin2.flip();
std::cout<<bin2.to_ullong()<<'\n';
Full code:
#include <iostream>
#include <bitset>
#include <string>
#include <format>
int main() {
//1
std::bitset<16> bin1;
//2
unsigned long long t=1145141919810;
std::bitset<16> bin2(t);
//3
std::string s3="dfdfddff";
std::bitset<16> bin3(s3,0,std::string::npos,'d','f');
//5
std::bitset<8> bin5("XXXXYYYY", 8, 'X', 'Y'); // [0,0,0,0,1,1,1,1]
std::cout<<std::format("{}\n{}\n{}\n{}\n",bin1.to_string(),bin2.to_string(),bin3.to_string(),bin5.to_string());
//element access
std::cout<<bin2[11]<<'\n'<<bin2.test(11)<<'\n';
if (bin2.any()){
std::cout<<"any\n";
}
std::cout<<bin2.count()<<'\n';
//capacity
std::cout<<bin2.size()<<'\n';
//modifiers
bin2^=1;
bin2<<=15;
bin2.set(0);
bin2.reset(1);
bin2.flip();
std::cout<<bin2.to_ullong()<<'\n';
return 0;
}
result:
0000000000000000
0000000001000010
0000000001010011
00001111
0
0
any
2
16
32766
example useage
Codeforces Round 958 (Div. 2)C. Increasing Sequence with Fixed OR
#include <iostream>
#include <chrono>
#include <ranges>
#include <vector>
#include <numeric>
#include <cmath>
#include <format>
#include <set>
#include <bitset>
int main() {
int n;
std::cin>>n;
for (int i = 0; i < n; ++i) {
long long a;
std::cin>>a;
bool isFind= false;
for (long long j = 1; j <=9007199254740992 ; j*=2) {
if (a==j){
std::cout<<1<<'\n'<<a<<'\n';
isFind= true;
break;
}
}
if (isFind){
continue;
}
std::bitset<500100> bin(a);
std::cout<<bin.count()+1<<'\n';
for (int j = bin.size()-1; j >=0 ; --j) {
if (bin[j]){
bin.flip(j);
std::cout<<bin.to_ullong()<<" ";
bin.flip(j);
}
}
std::cout<<a<<'\n';
}
return 0;
}
评论区