why is cin/cout slower than scanf/ printf

Nee*_*lex -3 c++ c++11 c++14

#include <iostream>
using namespace std;

int main(){
    int t;
    long long int n,res,x;
    scanf("%d",&t);
    while(t--){
            scanf("%lld",&n);
            res=0;


    for(int i=0;i<n;i++){
            scanf("%lld",&x);
            res^=x;
    }
    if(res==0)
        printf("-1\n");
    else 
        printf("%lld\n",res);

}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

this same program when i used cin and cout was timed out in hackerearth. But passed with scanf and printf.

Tej*_*dra 6

速度差异主要是由于 iostream I/O 函数与 CI/O 函数保持同步。我们可以通过调用来关闭它std::ios::sync_with_stdio(false);

默认情况下,标准 C++ 流在每次输入/输出操作后都会同步到标准 C 流。

一旦关闭同步,C++标准流就可以独立缓冲它们的I/O,你可以尝试看看所花费的时间几乎相似(可能小于scanf)