关于C/CPP的快读

发布时间 2023-11-27 22:28:12作者: 最最最長的電影
#include <cstdio>

class BufferIO {
public:
    template<typename T>
    auto operator>>(T& x);

    template<typename T>
    inline void unsigned_read(T& x);

    template<typename T>
    auto operator<<(T x);

    template<typename T>
    inline void unsigned_print(T x);

    ~BufferIO();

private:
    char io_stream[1000000]{};

    char bufferio[1000000]{};

    char bufferedWriter[1000000]{};

    char* p1 = bufferio;

    char* p2 = bufferio;

    char* p3 = bufferedWriter;

    char getchar();

    void putchar(char x);
};

char BufferIO::getchar() {
    if (p1 == p2 && (p2 = (p1 = bufferio) + fread(bufferio, 1, 1000000, stdin), p1 == p2)) {
        return EOF;
    }
    else {
        return *p1++;
    }
}

void BufferIO::putchar(char x) {
    *p3++ = x;
    if (p3 - bufferedWriter >= 1000000) {
        p3 = bufferedWriter;
        *p3++ = x;
    }
}

BufferIO::~BufferIO() {
    fwrite(bufferedWriter, p3 - bufferedWriter, 1, stdout);
}

template<typename T>
auto BufferIO::operator<<(T x) {
    int len = 0;
    if (x < 0) {
        x = -x;
        putchar('-');
    }
    while (x) {
        io_stream[len++] = x % 10 + '0';
        x /= 10;
    }
    while (len--) {
        putchar(io_stream[len]);
    }
}

template<typename T>
auto BufferIO::operator>>(T& x) {
    x = 0;
    int f = 1;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-') {
            f = -1;
        }
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        x = (x << 3) + (x << 1) + (c ^ 48);
        c = getchar();
    }
    x *= f;
}

template<typename T>
void BufferIO::unsigned_print(T x) {
    int len = 0;
    while (x) {
        io_stream[len++] = x % 10 + '0', x /= 10;
    }
    while (len--) {
        putchar(io_stream[len]);
    }
}

template<typename T>
void BufferIO::unsigned_read(T& x) {
    x = 0;
    char c = getchar();
    while (c < '0' || c > '9') {
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
    }
}