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

发布时间 2023-10-17 16:04:41作者: NexusXian

前言

初入算法,人工遍历全网。对于一些基本的题目要求有所了解,这里记录一下网上copy到的一些快读快写的模板,以方便与各位读者共勉。

Method 1 关闭同步/解除绑定

std::ios::sync_with_stdio(false);
std::cin.tie(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'
}

依旧看不懂,模板较长,但可以混用输入输出。
后面补解析(油专菜鸟学会了再说,暂时先做记录)