C++中的读入输出优化及清新脱俗的宏命令

C和C++有了#define,从此它就变了模样

宏命令就是#define,#if,#error之类的

本文主要介绍宏命令和相关的骚操作

读入输出优化

inline int read()
{
    int ans=0,f=1;
    char c=getchar();
    while (!isdigit(c))
    {
        if (c=='-')
            f=-1;
        c=getchar();
    }
    while (isdigit(c))
    {
        ans=(ans<<3)+(ans<<1)+(c^48);
        c=getchar();
    }
    return ans;
}

void write(const int& x)
{
    if (x<0)
    {
        putchar('-');
        write(-x);
    }
    if (x<10)
    {
        putchar(x+'0');
        return 0;
    }
    write(x/10);
    putchar(x%10+'0');
}

这是比较基础的

如果没有负数可以再改一下

inline int read()
{
    int ans=0;
    char c=getchar();
    while (!isdigit(c))
        c=getchar();
    while (isdigit(c))
    {
        ans=(ans<<3)+(ans<<1)+(c^48);
        c=getchar();
    }
    return ans;
}

void write(const int& x)
{
    if (x<10)
    {
        putchar(x+'0');
        return 0;
    }
    write(x/10);
    putchar(x%10+'0');
}

上次看到一份神级读优:

#include <cstdio>
#include <cctype>
struct IO
{
    #define S 32768
    char buf[S];int len = 0,pos = 0;
    char buf2[S],*p = buf2;
    inline char __getchar()
    {
        if (pos == len)pos = 0,len = fread(buf,1,S,stdin);if(pos == len)return '\0';
        return buf[pos++];
    }
    inline void __putchar(char c) {if(p == buf2 + S)fwrite(buf2,1,S,stdout),p = buf2;*p++ = c;}
    inline void flush(){fwrite(buf2,1,p - buf2,stdout);}
    inline int getint()
    {
        register int num = 0;register char ch = __getchar();for(;!(isdigit(ch));ch = __getchar());
        for(;isdigit(ch);ch = __getchar())num = (num << 3) + (num << 1) + (ch ^ '0');return num;
    }
    inline void putint(int x){if(x < 0){__putchar('-');x = -x;}if(x > 9)putint(x / 10);__putchar(x % 10 + 48);}
    inline void putll(int x){if(x < 0){__putchar('-');x = -x;}if(x > 9)putll(x / 10);__putchar(x % 10 + 48);}
    inline void newline(){__putchar(10);}
    inline char getupper(){register char ch = __getchar();for(;!isupper(ch);ch = __getchar());return ch;}
}io;

lld

我们经常用long long,而long long格式化输出有%I64d和%lld两种,有时又只能用一种

那只需要加这段语句就好了:

#ifdef WIN32
#define lld "%I64d"
#else
#define lld "%lld"
#endif

输出的时候:

printf("a="lld",b="lld,a,b);

当然最好还是用cout或手写

调试语句

调试时候一般用gdb

然而gdb很容易炸

于是只好用输出中间值

然后忘了注释,然后挂了

其实C++里有一个输出流:cerr

它可以无视文件操作而输出到屏幕上

也就是说,在NOIP中,你即使忘了删也不会出错

当然最好还是删了,毕竟运行需要时间

用法和cout一样

cerr<<a<<' '<<b<<endl;

你输出了中间值,然而发现根本不知道哪个值是什么变量
那就加一句:

#define debug(x) cerr<<#x<<':'<<x<<endl

#x表示标识符x实际代表的变量名。注意只能在#define中使用

这样,就可以直接调用debug来输出中间值了

占坑,想到再写吧

猜你喜欢

转载自www.cnblogs.com/lstoi/p/9502252.html