C++快读快写

前言

在做题的时候经常会遇到卡输入输出的题,连scanf和printf都会TLE的题,我们需要使用快读快写。

基本快读快写

当然,基本快读快写是指整数的快读快写

快读

inline int read()
{
    int X = 0, w = 0; char ch = 0;
    while (!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while (isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}

这里的inline可以加速,还有x = (x << 1) + (x << 3) + (c ^ 48);使用位运算加快速度。

f变量可以判负数。如果没有用bits/stdc++.h的头文件,isdigit函数要用cctype头文件,当然也有人把isdigit替换为手写ASCII码判断,但isdigit可能会更快。

快写

inline void write(int x)
{
     if (x < 0) putchar('-'), x = -x;
     if (x > 9) write(x / 10);
     putchar(x % 10 + '0');
}

快写代码要短一些,这里采用递归写法, 可以用inline优化,putchar比cout和printf要快。

高级快读快写

来自某洛谷大佬cyffff (%%%orz)

namespace IO { // by cyffff
int len = 0;
char ibuf[(1 << 20) + 1], *iS, *iT, out[(1 << 25) + 1];
#define gh()                                                                   \
    (iS == iT ? iT = (iS = ibuf) + fread(ibuf, 1, (1 << 20) + 1, stdin),       \
     (iS == iT ? EOF : *iS++) : *iS++)
#define reg register
inline int read() {
    reg char ch = gh();
    reg int x = 0;
    reg char t = 0;
    while (ch < '0' || ch > '9')
        t |= ch == '-', ch = gh();
    while (ch >= '0' && ch <= '9')
        x = x * 10 + (ch ^ 48), ch = gh();
    return t ? -x : x;
}
inline void putc(char ch) {
    out[len++] = ch;
}
template <class T> inline void write(T x) {
    if (x < 0) putc('-'), x = -x;
    if (x > 9) write(x / 10);
    out[len++] = x % 10 + 48;
}
inline void flush() {
    fwrite(out, 1, len, stdout);
    len = 0;
}
} // namespace IO
using IO::flush;
using IO::putc;
using IO::read;
using IO::write;

后记

如有不足,请大佬在评论区指出,本蒟蒻一定会关注回复。
注:可以在我的 cnblogs 里查看。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值