C++ 快速读入 输出优化模板

前言

Method 1 关闭同步/解除绑定

std::ios::sync_with_stdio(false),std::cin.tie(0),cout(0);

原理:关闭同步流
ps. 此时cin cout与scanf同printf 会混乱,不要混用。

Method 2 快读、快写

template <typename T>
inline T read() 
{ 
 	//声明 template 类, 要求提供输入的类型 T, 并以此类型定义内联函数 read()
	T sum = 0, fl = 1; // 将 sum,fl 和 ch 以输入的类型定义
	int ch = getchar();
	for (; !isdigit(ch); ch = getchar())
	if (ch == '-') fl = -1;
	for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0';
	return sum * fl;
}
template <typename T>
inline void write(T x) 
{
    static int sta[35];
    int top = 0;
    do {
        sta[top++] = x % 10, x /= 10;
    } while (x);
    while (top) putchar(sta[--top] + 48); // 48 是 '0'
}
posted @ 2023-10-17 15:52  NexusXian  阅读(255)  评论(0)    收藏  举报
Nephrenn‘s Blog