As it is known that C scanf/printf works faster for Input/Output compared to cin/cout of C++.
I read in some blogs that adding the following
"std::ios_base::sync_with_stdio(false);" in a C++ code makes it run faster? Does it also increases the speed of Input/Output?
--------------------------------------------------------------------------------
So I tried to test this fact on the following problem:
http://www.codechef.com/problems/TSORT
Here are the two solutions to the problem:
1) Using std::cin/cout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
std::ios_base::sync_with_stdio(false);
int n; std::cin >>n; int a[n];
for(int i=0;i<n;i++)
std::cin >>a[i];
sort(a,a+n);
for(int i=0;i<n;i++)
std::cout<<a[i]<<endl;
return 0;
}
|
--------------------------------------------------------------------------------
2. Using scanf/printf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
int n; scanf("%d",&n); int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
for(int i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}
|
-------------------------------------------------------------------------------
Surprisingly enough, the second code runs within time limit of 5 seconds while the first one gives Time limit exceeded.
Why is this happening? Please help me out.
Also, Please suggest some ways to fasten the input/output in C++. Thanks