盘点3个你不知道的的c++小技巧(初学者)

1. __int128_t (快读和快写)

1.1 什么时候使用__int128_t

众所周知,某些毒瘤题计算出的数值long long说不定都存不下:

这时候,你会选择高精度吗?

其实,__int128_t才是最好的选择,如果int128都过不了,那么还是先跳过吧,对于初学者来说,高精注意点太多,码量较大,与其死磕,不如做下一道题。

1.2 __int128_t的基本介绍

顾名思义,__int128_t的范围是2^{^{127}}-1,用起来和普通int (long long) 没什么区别,只是不能用cin, cout, scanf, printf而已,需要我们手写快读和快写,原理就是模拟,但速度却是scanf、printf的4、5倍,附上代码(我用的是define,可以方便很多,这里是A + B问题):

#include<bits/stdc++.h>
using namespace std;
#define int __int128_t
typedef pair<int, int> PII;
#define endl '\n'
const int N = 1e8;
#define For(i, a, b) for(int i = a;i <= b;i++)
int read(){
    int x = 0;
    int f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9'){
        if (ch == '-'){
            f = -1;
        }
        ch = getchar();
    }
    while ('0' <= ch && ch <= '9'){
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
void write(int res){
    if(res > 9){
        write(res / 10);
    }
    putchar(res % 10 + '0');
}
signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int x, y;
    x = read();
    y = read();
    write(x + y);
    return 0;
}

2. lower_bound, uper_bound, binary_search

自己写二分老是写不对?那就用STL的lower_bound, uper_bound, binary_search:绝对标准。

不过注意,这三个函数返回的是地址,上代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int, int> PII;
#define endl '\n'
const int N = 1e8;
#define For(i, a, b) for(int i = a;i <= b;i++)
int read(){
    int x = 0;
    int f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9'){
        if (ch == '-'){
            f = -1;
        }
        ch = getchar();
    }
    while ('0' <= ch && ch <= '9'){
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
void write(int res){
    if(res > 9){
        write(res / 10);
    }
    putchar(res % 10 + '0');
}
int a[] = {1, 2, 5, 4, 7};
signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cout << upper_bound(a, a + 5, 3) - a << '\n';
    cout << lower_bound(a, a + 5, 3) - a << '\n';
    return 0;
}

文章不定期更新,三连必回!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值