C++ 读入/输出优化

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

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



(一)手写优化


版本1:

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

#include <iostream>
#include <cstdio>
#include <cctype>
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 <iostream>
#include <cstdio>
#include <cctype>
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了,会混乱的..

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值