您的位置:首页 > 移动开发 > IOS开发

读入外挂 std::ios::sync_with_stdio(false);

2017-08-09 11:13 363 查看
在此郑重说明,这是水的一篇博客,哈哈哈哈哈。

读入外挂

当遇到坑的题scanf都过不了的时候就用这个,不过这样的情况一般都是代码效率问题。

#include <bits/stdc++.h>
using namespace std;
inline int Scan()  //inline为内联函数,目的是预处理,可减少时间
{
int res = 0, ch, flag = 0;

if((ch = getchar()) == '-')             //判断正负
flag = 1;

else if(ch >= '0' && ch <= '9')           //得到完整的数
res = ch - '0';
while((ch = getchar()) >= '0' && ch <= '9' )
res = res * 10 + ch - '0';

return flag ? -res : res;
}
int main()
{
int n=Scan();
printf("%d\n",n);
}


当然上面的也可以换成
long long
类型的

cin的小技巧

ios::sync_with_stdio(false);


可以将cin和scanf的效率相匹敌。

详情说明:

scanf在Linux平台上测试结果为2.01秒

const int MAXN = 10000000;
int numbers[MAXN];
void scanf_read()
{
freopen("data.txt","r",stdin);
for (int i=0;i<MAXN;i++)
scanf("%d",&numbers[i]);


cinLinux平台上测试结果为6.38秒

const int MAXN = 10000000;

int numbers[MAXN];

void cin_read()
{
freopen("data.txt","r",stdin);
for (int i=0;i<MAXN;i++)
std::cin >> numbers[i];
}


cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?只需一个语句
std::ios::sync_with_stdio(false);
,这样就可以取消cin于stdin的同步了。

const int MAXN = 10000000;

int numbers[MAXN];

void cin_read_nosync()
{
freopen("data.txt","r",stdin);
std::ios::sync_with_stdio(false);
for (int i=0;i<MAXN;i++)
std::cin >> numbers[i];
}


取消同步后效率究竟如何?经测试运行时间锐减到了2.05秒,与scanf效率相差无几了!有了这个以后可以放心使用cin和cout了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: