Optimized Input and Output in C++

Background

C++标准库<iostream>中的cin, cout相比<cstdio>中的scanf, printf要方便许多,但速度也较为缓慢。在输入输出的数据类型不是很特殊时,可以使用以下代码来代替cin, cout(要包含<cctype>, <cstdio>,不要包含<iostream>)。

Code

class InputStream {
private:
  static int const BUFFER_SIZE = 10000000;
  char *buffer;

public:
  InputStream() {
    buffer = new char[BUFFER_SIZE]();
    fread(buffer, sizeof(char), BUFFER_SIZE, stdin);
  }
  InputStream &operator>>(int &n) {
    for (; *buffer < '0' || *buffer > '9'; ++buffer)
      ;
    for (n = 0; *buffer >= '0' && *buffer <= '9';
         (n *= 10) += *(buffer++) - '0')
      ;
    return *this;
  }
  InputStream &operator>>(char &c) {
    for (; !isprint(*buffer) || *buffer == ' '; ++buffer)
      ;
    c = *(buffer++);
    return *this;
  }
  InputStream &operator>>(char *s) {
    char *t = s;
    for (; !isprint(*buffer) || *buffer == ' '; ++buffer)
      ;
    for (; isprint(*buffer) && *buffer != ' '; *(t++) = *(buffer++))
      ;
    *t = '\0';
    return *this;
  }
} cin;

class OutputStream {
private:
  static int const BUFFER_SIZE = 10000000;
  char *buffer, *cur;

public:
  OutputStream() { buffer = cur = new char[BUFFER_SIZE](); }
  ~OutputStream() { fwrite(buffer, sizeof(char), cur - buffer, stdout); }
  OutputStream &operator<<(int const &n) {
    for (sprintf(cur, "%d", n); *cur; ++cur)
      ;
    return *this;
  }
  OutputStream &operator<<(char const &c) {
    *(cur++) = c;
    return *this;
  }
  OutputStream &operator<<(char *s) {
    for (char *t = s; *t; *(cur++) = *(t++))
      ;
    return *this;
  }
} cout;

static char const endl = '\n';

RegMs If

418 I'm a teapot

Leave a Reply

Your email address will not be published. Required fields are marked *