uint32_t reverseBits(uint32_t n) {
string s = bitset<32>(n).to_string();
reverse(s.begin(), s.end());
return bitset<32>(s).to_ulong();
}
字符串分割
将字符串按照空格分割
string s = "hello world my name is yao jun";
stringstream ss(s);
string str;
int cnt = 0;
while(ss >> str){
cnt++;
cout<
执行结果:
hello
world
my
name
is
yao
jun
7
四舍五入保留小数
char str[10];
double num = 22.23434;
sprintf(str, "%.2f", num);
string s = str;
cout<
执行结果
22.23
字符串按格式拆分
string a = "12:59:36";
char str2[100];
memcpy(str2, a.c_str(), strlen(a.c_str()));
int u, v, w;
sscanf(str2, "%d:%d:%d", &u, &v, &w);
cout<
执行结果:
12 59 36
相同字符的字符串
string s(10, 'a');
cout<
执行结果:
aaaaaaaaaa
结构体排序
struct node{
int a, b;
// 从小到大排序
bool operator < (const node& node_)const{
if(a != node_.a) return a < node_.a;
return b < node_.b;
}
};
int main(){
vector tt;
tt.push_back({1,5});
tt.push_back({2,3});
sort(tt.begin(), tt.end());
for(auto &node: tt){
cout<
执行结果:
1 5
2 3
优先队列自定义排序
struct node{
int a, b;
// 在优先队列中,跟排序的规则是反的,这里是指a大的排在前面,a相同时,b大的排在前面
bool operator < (const node& node_)const{
if(a != node_.a) return a < node_.a;
return b < node_.b;
}
};
int main(){
priority_queue pq;
pq.push({1,5});
pq.push({2,3});
pq.push({2,5});
while(!pq.empty()) {
cout<
执行结果
2 5
2 3
1 5



