C++ 读入/输出优化

考试时若题目有大量输入输出,最好使用读入/输出优化.

scanf与printf比cin和cout快,而getchar和putchar是最快的(这两个函数本是读/写一个字符的,这里用作优化).



(一)手写优化


版本1:

:isdigit(x)判断x是否为十进制整数

#include 
#include 
#include 
using namespace std;

int Read() {
	char c;
	int ans = 0;
	bool Sign = false;
	while(!isdigit(c=getchar()) && c != '-');    //去除非法字符
	if(c == '-') {
		Sign = true;
		c = getchar();
	}
	do {
		ans = ans * 10 + (c - '0');
	}while(isdigit(c=getchar()));
	return Sign ? -ans : ans;
}

void Write(int x) {
	if(x < 0) {
		putchar('-');
		x = -x;
	}
	if(x >= 10) Write(x / 10);
	putchar(x % 10 + '0');
}

int main() {
	int a;
	a = Read();
	Write(a);
	return 0;
}


版本2:在某些地方再优化


1> inline关键字.一般将不是很复杂调用次数多的函数定义为inline(内联函数),在编译时,编译器会把该函数的代码副本放置在每个调用该函数的地方。这与define相似,可以提高速度.(不要滥用于长函数)

 

2> ans * 10改为了位运算:(ans << 3)+(ans << 1).

ans<<3就是ans*23 ans*8

同理,ans<<1就是ans*2;

因此(ans << 3)+(ans << 1)ans*10是相同的,在运算速度上有所提升;

 

#include 
#include 
#include 
using namespace std;

inline int Read() {
	char c;
	int ans = 0;
	bool Sign = false;
	while(!isdigit(c=getchar()) && c != '-'); 
	if(c == '-') {
		Sign = true;
		c = getchar();
	}
	do {
		ans = (ans<<3) + (ans<<1) + (c - '0');
	}while(isdigit(c=getchar()));
	return Sign ? -ans : ans;
}

inline void Write(int x) {
	if(x < 0) {
		putchar('-');
		x = -x;
	}
	if(x >= 10) Write(x / 10);
	putchar(x % 10 + '0');
}

int main() {
	int a;
	a = Read();
	Write(a);
	return 0;
}


(二)优化cin、cout

要是不会scanf和printf,也不手写优化,那就在主函数第一句写上:

ios::sync_with_stdio(false);


这取消了cin、cout与scanf、printf的同步,可以加快速度,但不可再用scanf、printf了,会混乱的..

你可能感兴趣的:(C++ 读入/输出优化)