C++ 增加预处理宏的方法

C++ 增加预处理宏的方法

前几天写题的时候发现,我使用的fread在oj上并没有比执行了ios::sync_with_stdio(false)cin更快,最后发现并不是fread的问题,而是因为我增加了这样一条信息

#ifdef _WIN32
	return getchar();
#endif

而在一些oj上,评测环境也是windows,所以导致了我的fread直接变成getchar()了,而使用getchar()进行快读日常负优化,我就开始找怎么避免这个问题,最后发现可以编译时可以在本地增加预处理宏,具体如下

"-D MACRO_NAME macro.c", //增加预处理宏

这样就会在编译时增加一个MACRO_NAME的宏,然后把ifdef后面的_WIN32换成你定义的宏名称即可

对于vscode,直接在tasks.json中的args参数中增加这一条指令即可

fread模板

最后附一下更新后的fread模板

struct READ {
    inline char read() {
    #ifdef Artoriax
        return getchar();
    #endif
        const int LEN = 1 << 18 | 1;
        static char buf[LEN], *s, *t;
        return (s == t) && (t = (s = buf) + fread(buf, 1, LEN, stdin)), s == t ? -1 : *s++;
    }
    inline READ & operator >> (char *s) {
        char ch;
        while (isspace(ch = read()) && ~ch);
        while (!isspace(ch) && ~ch) *s++ = ch, ch = read(); *s = '';
        return *this;
    }
    inline READ & operator >> (string &s) {
        s = ""; char ch;
        while (isspace(ch = read()) && ~ch);
        while (!isspace(ch) && ~ch) s += ch, ch = read();
        return *this;
    }
    template <typename _Tp> inline READ & operator >> (_Tp&x) {
        char ch, flag;
        for(ch = read(),flag = 0; !isdigit(ch) && ~ch; ch = read()) flag |= ch == '-';
        for(x = 0; isdigit(ch); ch = read()) x = x * 10 + (ch ^ '0');
        flag && (x = -x);
        return *this;
    }
} in;

可以直接读入字符串了,对于double类型没有特意去写,感觉没有必要。

原文地址:https://www.cnblogs.com/artoriax/p/13596369.html