我想在我的代码中使用快速输入和输出.我理解使用getchar_unlocked以下功能进行快速输入.
inline int next_int() {
int n = 0;
char c = getchar_unlocked();
while (!('0' <= c && c <= '9')) {
c = getchar_unlocked();
}
while ('0' <= c && c <= '9') {
n = n * 10 + c - '0';
c = getchar_unlocked();
}
return n;
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释我如何使用putchar_unlocked()功能快速输出?
我正在经历这个问题,有人说putchar_unlocked()可以用来快速输出.
以下代码适用于使用putchar_unlocked()的快速输出.
#define pc(x) putchar_unlocked(x);
inline void writeInt (int n)
{
int N = n, rev, count = 0;
rev = N;
if (N == 0) { pc('0'); pc('\n'); return ;}
while ((rev % 10) == 0) { count++; rev /= 10;} //obtain the count of the number of 0s
rev = 0;
while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;} //store reverse of N in rev
while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;}
while (count--) pc('0');
}
Run Code Online (Sandbox Code Playgroud)
通常Printf的输出速度非常快,但是对于写入整数或长输出,下面的函数有点快.
这里我们使用putchar_unlocked()方法输出一个类似于putchar()的类似线程不安全版本的字符,并且速度更快.