关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流

笔试比赛等注意事项:
关于cin coutscanf printf。做题的时候尽量使用scanf printf。下面告诉你一个小常识,不要惊讶:cin coutscanf printf慢20倍左右!

一旦遇到大数据量,光是读入就有可能跪掉。

你或许可以使用std::ios::sync_with_stdio(false);这条语句关掉scanfcin 的同步加快效率。但是即使是这样cin 还要慢 5倍左右,而且一旦使用了这条语句,scanfcin 混用可能就会造成一些奇怪的问题。

转自牛客网


在网上查看别人的ACM代码时,发现别人输入输出语句用的总是scanf与printf,有点不解,还以为他们用的都是C语言,而非C++,但今天做的一道题(Sort):

发现与网上的其他高手使用完全相同的方法,使用scanf及printf的代码提交后Accepted,而使用cin及cout的却Time Limit Exceeded,代码如下:

代码一(Accepted):

#include<iostream>
using namespace std;
bool a[1000001];
int main()
{
    int n, m, num, count;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(a, 0, sizeof(a));
        for(int i=0; i<n; i++)
        {
            scanf("%d",&num);
            a[num + 500000] = 1;
        }
        count = 0;
        for(int j = 1000000; j >= 0; --j)
        {
            if(a[j])
            {
                if(count == m - 1)
                {
                    printf("%d\n",j-500000);
                    break;
                }
                printf("%d ",j-500000);
                count++;
            }
        }
    }
    return 0;
}

代码二(Time Limit Exceeded):

#include<iostream>
using namespace std;
bool a[1000001];
int main()
{
    int n, m, num, count;
    while(cin >> n >> m){
    memset(a, 0, sizeof(a));
    for(int i=0; i<n; i++)
    {
        cin >> num;
        a[num + 500000] = 1;
    }
    count = 0;
    for(int j = 1000000; j >= 0; --j)
    {
        if(a[j])
        {
            if(count == m - 1)
            {
                cout << j - 500000 << endl;
                break;
            }
            cout << j - 500000 << " ";
            count++;
        }
    }
}
return 0;
}

可以看出,代码思路完全一样,只是输入输出方法不同,加上这一句代码后使用cin及cout也可以Accepted:

std::ios::sync_with_stdio(false);

原来而cin,cout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入 输出缓存,可以节省许多时间,使效率与scanf与printf相差无几.

tie
tie是将两个stream绑定的函数,空参数的话返回当前的输出流指针。

#include <iostream>
#include <fstream>

int main(int argc, char *argv[])
{
    std::ostream *prevstr;
    std::ofstream ofs;
    ofs.open("test.txt");

    std::cout << "tie example:\n"; // 直接输出到屏幕

    *std::cin.tie() << "This is inserted into cout\n"; // 空参数调用返回默认的output stream,也就是cout
    prevstr = std::cin.tie(&ofs); // cin绑定ofs,返回原来的output stream
    *std::cin.tie() << "This is inserted into the file\n"; // ofs,输出到文件
    std::cin.tie(prevstr); // 恢复

    ofs.close();
    system("pause");
    return 0;
}

输出:

tie example:
This is inserted into cout
请按任意键继续. . .

sync_with_stdio
这个函数是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流绑到了一起。

猜你喜欢

转载自blog.csdn.net/qq_38365116/article/details/80463919