跳到正文

个人记录

快读快写(卡常版)

ccxXF约 5 分钟
原文

这是 2026年4月25日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年3月7日
收录
2026年4月25日
更新
2026年11月22日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1
C++
namespace FastIO {
	const int BUFFER_SIZE = 1 << 20;  // 1MB 缓冲区
	
	// 输入缓冲区
	char in_buf[BUFFER_SIZE];
	char *in_ptr = in_buf;
	char *in_end = in_buf;
	
	// 输出缓冲区
	char out_buf[BUFFER_SIZE];
	char *out_ptr = out_buf;
	
	// 从 stdin 读取数据到输入缓冲区
	inline void load() {
		in_end = in_buf + fread(in_buf, 1, BUFFER_SIZE, stdin);
		in_ptr = in_buf;
	}
	
	// 获取一个字符(带缓冲)
	inline char getchar() {
		if (in_ptr == in_end) {
			load();
			if (in_ptr == in_end) return EOF;
		}
		return *in_ptr++;
	}
	
	// 输出一个字符(带缓冲)
	inline void putchar(char c) {
		if (out_ptr == out_buf + BUFFER_SIZE) {
			fwrite(out_buf, 1, BUFFER_SIZE, stdout);
			out_ptr = out_buf;
		}
		*out_ptr++ = c;
	}
	
	// 刷新输出缓冲区
	inline void flush() {
		fwrite(out_buf, 1, out_ptr - out_buf, stdout);
		out_ptr = out_buf;
	}
	
	// 读取整数(支持负数)
	template <typename T>
	inline bool read(T &x) {
		x = 0;
		char c = getchar();
		bool negative = false;
		// 跳过空白字符
		while (c != EOF && isspace(c)) c = getchar();
		if (c == EOF) return false;
		if (c == '-') {
			negative = true;
			c = getchar();
		}
		while (c != EOF && isdigit(c)) {
			x = x * 10 + (c - '0');
			c = getchar();
		}
		if (negative) x = -x;
		return true;
	}
	// 读取字符串(以空白字符分隔)(string)
	inline bool read(std::string &s) {
		s.clear();
		char c = getchar();
		while (c != EOF && isspace(c)) c = getchar();
		if (c == EOF) return false;
		while (c != EOF && !isspace(c)) {
			s.push_back(c);
			c = getchar();
		}
		return true;
	}
	// 读取字符串(以空白字符分隔)(char)
	inline bool read(char *s) {
		char c = getchar();
		while (c != EOF && isspace(c)) c = getchar();
		if (c == EOF) return false;
		while (c != EOF && !isspace(c)) {
			*s++ = c;
			c = getchar();
		}
		*s = '\0';
		return true;
	}
	
	// 输出整数
	template <typename T>
	inline void write(T x) {
		if (x < 0) {
			putchar('-');
			x = -x;
		}
		char tmp[40];
		int len = 0;
		do {
			tmp[len++] = '0' + (x % 10);
			x /= 10;
		} while (x);
		while (len--) putchar(tmp[len]);
	}
	
	// 输出字符串
	inline void write(const char *s) {
		while (*s) putchar(*s++);
	}
	
	// 输出换行
	inline void writeln() {
		putchar('\n');
	}
	
	// 输出整数并换行
	template <typename T>
	inline void writeln(T x) {
		write(x);
		putchar('\n');
	}
	
	// 输出字符串并换行
	inline void writeln(const char *s) {
		write(s);
		putchar('\n');
	}
}  // namespace FastIO