问题
见输入输出编程题:计算一系列数的和
有篇答案如下:
#include <string>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
using ll = long long;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
while (cin >> n)
{
if( n ==0) break;
int res = 0;
int m;
while (n--)
{
cin >> m;
res += m;
}
cout << res << endl;
}
return 0;
}
运行时间:4ms,同比其他C++答案效率更高。答案中两句代码吸引了我的注意:
ios_base::sync_with_stdio(false);
cin.tie(NULL);
查阅资料,整理如下。
解释
cin 慢是有原因的,默认情况下,cin 与 stdin 总是保持同步的,也就是说这两种方法可以混用,不必担心文件指针混乱,同时 cout 和 stdout 也一样,两者混用不会输出顺序错乱。正是为了这个兼容的特性,导致 cin 有许多额外的开销,如何禁用这个特性呢?只需一个语句
std::ios::sync_with_stdio(false);,这样就可以取消 cin 和 stdin 的同步了。
std::ios::sync_with_stdio(); 是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流绑到了一起。也就是 C++标准streams(cin,cout,cerr…) 与相应的C标准程序库文件(stdin,stdout,stderr)同步,使用相同的 stream 缓冲区。
默认是同步的,但由于同步会带来某些不必要的负担,因此该函数作用是使得用户可以自行取消同步。
cin.tie(NULL) 取消 cin 和 cout 的绑定。
#include <iostream>
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
// IO
}
参考资料
提交区答案
ios::sync_with_stdio(false)详解
cin.tie与sync_with_stdio加速输入输出
版权声明:本文为kernelxiao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。