Here, I have to correct the idea that iostream is very slow.
We have observed that iostream is slow, usually because C ++ needs to maintain compatibility with C's Io library, so c ++'s Io library does not have a buffer, it must contain one character and one character!
For example, some people have such a pain point:
Getline (CIN, S );
Scanf ("% d", & I );
In this case, Getline can only read one character at a time. If it reads 100 characters at a time, it only uses 10 characters. The remaining 90 characters cannot be put back in stdin, in this case, the scanf is read from the wrong location. Therefore, to be compatible with C, the C ++ library has to read a single character. In this way, the iostream of C ++ is slow.
Fortunately, this behavior can be set. Cin. sync_with_stdio (false); this will make the iostream of C ++ faster. Of course, if you do this, you must ensure that the C Io library is not used.
The following is a test:
[Xxx @ YYY ~] $ Cat testcio. C & gcc-O3 testcio. C-o testcio. Out
# Include <stdio. h>
Int main (INT argc, char ** argv)
{
Char s [1024];
While (fgets (S, 1024, stdin ))
{
Printf ("% s", S );
}
}
[Xxx @ YYY ~] $ Cat testcxxio. cpp & G ++-O3 testcxxio. cpp-O testcxxio. Out
# Include <iostream>
Using namespace STD;
Int main (INT argc, char ** argv)
{
Cin. sync_with_stdio (false );
Char s [1024];
While (CIN. Getline (S, 1024, '\ n '))
Cout <S <Endl;
}
[Xxx @ YYY ~] $ Time for (I = 0; I <10; I ++); do./testcio. Out <some_text; done
...........
Real 0m7. 170 s
User 0m0. 957 s
Sys 0m1. 623 s
[Xxx @ YYY ~] $ Time for (I = 0; I <10; I ++); do./testcxxio. Out <some_text; done
...........
Real 0m7. 123 S
User 0m0. 742 s
Sys 0m1. 737 s
The speed is the same.