std::ios::sync_with_stdio(false)的运用

c++中cin,cout效率比较低,是因为先把要输出的东西存入缓冲区与C语言中的stdio同步后,再输出,导致效率降低,而这段语句的作用是取消缓冲区同步,直接使用,由此可节省时间,使效率与scanf与printf相差无几。
但需要注意的一点是,因为取消与stdio的同步之后,就不建议再使用 printf 与 scanf了,否则实际输出就会与预期不符。只能用cin 与 cout

读入外挂

当遇到坑的题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 cin_read()  
{  
    freopen("data.txt","r",stdin);  
    for (int i=0;i<MAXN;i++)  
        std::cin >> 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];  
}  

猜你喜欢

转载自blog.csdn.net/danshiming/article/details/114276411