2013-08-02 117 views
6

我希望用快速的输入和输出在我的代码。使用下面的函数,我明白了getchar_unlocked用于快速输入的用法。使用putchar_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; 
} 

有人请解释我如何使用putchar_unlocked()功能快速输出?

我所经历的this question有有人说putchar_unlocked()可用于快速输出。

+0

您使用的是C++还是c? – aaronman

+0

@aaronman我使用C++ –

+0

那么不这样做,因为你可能不需要它 – aaronman

回答

7

那么下面的代码适用于快速输出使用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'); 
    } 

通常printf的是相当快的产出,但是编写整数或长输出,下面的函数是一个稍微有点快。
这里我们使用putchar_unlocked()方法输出一个类似线程不安全的putchar()版本的字符,速度更快。

See Link.

+0

它检查仅数有一个“0 'seq最后的结果。如果数字在中间有'0'序列,则此功能不起作用。例如:12300023 – 648trindade

+0

@ 648trindade It Works。 –