栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++刷题常用技巧

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++刷题常用技巧

bitset
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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948527.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号