本文最后更新于 577 天前,其中的信息可能已经有所发展或是发生改变。
前几天分享了Go语言的快读代码,刚刚逛知乎,又发现了一则惊喜。
C++快读代码如下:
template<typename T>
void read(T &x) {
int f = 1;
x = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-')f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch ^ 48);
ch = getchar();
}
x *= f;
}
原理和之前Go语言的快读代码思路一致,利用getchar()函数,我们可以得到一个字节的ASCII码输入数据,因此,我们将ASCII码减去’0’就得到了一个十进制位,将这个十进制位拼凑起来就能得到一个完整的int类型数据,由于不存在scanf的字符串模板扫描过程,所以比scanf的效率高很多。当算法题目输入数据量极大的时候,我们可以使用快读的方式来读入输入数据,提高程序运行效率,避免在读入数据的过程中浪费冤枉时间。
顺便还附赠快写代码:
template<typename T>
void print(T x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) print(x / 10);
putchar(x % 10 + '0');
}
这篇知乎上还讲了重写IO流的方式,比getchar()方式更快(10ms左右),由于性能差距不大,代码复杂,在这里就不作探讨了,原帖在下面放出,有兴趣的可以自行研究。
IO流方式快读:
#include <bits/stdc++.h>
using namespace std;
struct InputOutputStream {
enum {
SIZE = 1000001
};
char ibuf[SIZE], *s, *t, obuf[SIZE], *oh;
bool eof;
InputOutputStream() : s(), t(), oh(obuf), eof(false) {}
~InputOutputStream() { fwrite(obuf, 1, oh - obuf, stdout); }
explicit operator bool() const {
return static_cast<bool>(eof == false);
}
inline char read() {
if (s == t) t = (s = ibuf) + fread(ibuf, 1, SIZE, stdin);
return s == t ? -1 : *s++;
}
inline InputOutputStream &operator>>(char *x) {
static char c;
for (c = read(); isspace(c); c = read())
if (c == -1) {
eof = true;
return *this;
}
for (; !isspace(c); c = read()) *x = c, ++x;
*x = 0;
return *this;
}
template<typename T>
inline InputOutputStream &operator>>(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) {
eof = true;
return *this;
}
iosig |= c == '-';
}
for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0');
if (iosig) x = -x;
return *this;
}
inline void print(char c) {
if (oh == obuf + SIZE) {
fwrite(obuf, 1, SIZE, stdout);
oh = obuf;
}
*oh++ = c;
}
template<typename T>
inline void print(T x) {
static int buf[40], cnt;
if (x != 0) {
if (x < 0) print('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48;
while (cnt) print((char) buf[cnt--]);
} else print('0');
}
template<typename T>
inline InputOutputStream &operator<<(const T &x) {
print(x);
return *this;
}
inline void print(const char *x) {
for (; *x; x++)
print(*x);
}
} io;
#ifndef DEBUG
#define cin io
#define cout io
#define endl '\n'
#endif
本文参考自知乎:
作者:Black
链接:https://www.zhihu.com/question/24456451/answer/1954251391