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

C++快读快写

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

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  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 里查看。

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

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

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