4

这是我的代码:

#include <stdio.h>

void scan(int* i)
{
    int t=0;
    char c;
    bool negative=false;
    c=getchar_unlocked();
    while(c<'0'&&c>'9')
    {
        if(c=='-')
            negative=true;
        c=getchar_unlocked();
    }
    while(c>'0'&&c<'9')
    {
        t=(t<<3)+(t<<1)+c-'0';
        c=getchar_unlocked();
    }
    if(negative)
        t=~(t-1); //negative
    *i=t;
}

int main(int argc, char const *argv[])
{
    int i;
    scan(&i);
    return 0;
}

我知道这里定义的函数 as比编程竞赛scan更快scanf并且非常有用。但由于某种原因,这段代码不能在 Windows 上运行,而是在 Linux 上运行。我该怎么做才能让它在 Windows 上运行?我正在使用g++Dev-C++ 的编译器。

4

3 回答 3

5

getchar_unlocked is not a C or C++ standard function and therefore it's no surprise that it doesn't work on Windows. It is a POSIX standard I think, but Windows compilers don't support all POSIX functions.

If you replaced getchar_unlocked with getchar, it would kind of work, although the algorithm doesn't seem quite right.

You could do this with conditional compilation, like this for instance

#ifdef _WINDOWS
// no getchar_unlocked on Windows so just call getchar
inline int getchar_unlocked() { return getchar(); }
#endif
于 2012-10-22T11:38:06.087 回答
2

Windows 具有等效的_getchar_nolock,它是特定于Windows 的。

请参阅此链接:

https://msdn.microsoft.com/en-us/library/4y2e9z0c.aspx

因此,如果您对非线程安全版本感到满意并且希望获得最佳性能,您可以执行以下操作:

#ifdef WIN32
// no getchar_unlocked on Windows so call _getchar_nolock
inline int getchar_unlocked() { return _getchar_nolock(); }
#endif
于 2017-11-11T23:06:22.567 回答
0

getchar_unlocked()主要用于竞争性编程,但是,如果您想在其他地方使用它,只需确保一次只有 1 个线程在使用它。同样适用于 putchar_unlocked() 函数。它是 POSIX 等价物,因此 Windows 编译器不支持它。但是,您可以使用以下两种中的任何一种-

  1. 正常的速度

    int getchar_unlocked() { return getchar(); } 无效 putchar_unlocked(char _c) { putchar(_c); }

  2. 速度快

    int getchar_unlocked() { return _getchar_nolock(); } 无效 putchar_unlocked(char _c) { _putchar_nolock(_c); }

于 2018-03-09T18:37:24.357 回答