Detailed optimization read read

Read read optimization:

  We all know C ++, there are many ways to read, there is in the iostream cin, and stdio in the scanf, in both reading function also has a good or bad points, cin speeds far less than scanf, because cin association when you enter a lot of things, slow down its speed, I tried to get concerned about how cin speed to go up.

 

cin speed:

  We wrote before entering such a sentence: std :: ios :: sync_with_stdio (false); and the operation can be associated cin canceled, so that you can speed up to cin, cin and scanf about the speed almost.

getchar () optimization:

  This is the most common method of reading, C ++ in machine-readable string of digital speed than the reading speed a lot faster, we can number into a numeric character to a read, using multiplications and additions to store so that you can greatly speed up the read speed, do not think much computing speed is slow, it's probably time scanf speed of 10 times faster.

  We first define an integer variable f = 1, reads the first character, if it is '-' then f = -1, otherwise unchanged, this character represents the digital value into x, the following while, constantly read data, the read data for new, x = x * 10 + character -'0 ';

  Cycling conditions were read into this character is a number of characters, if not come out, and finally do not forget to x = x * f; determining the sign reads completed.

Code:

void Read ( int & x) // & x means taking address, if the function in the value of change of x changes with the value of the outside 
{
     int F = . 1 ;
     char CZ; 
    CZ = getchar ();
     IF (CZ == ' - ' ) { 
        F = - . 1 ; 
        CZ = getchar (); 
    } 
    the while (CZ <= ' . 9 ' && CZ> = ' 0 ' ) 
    { 
        X = X * 10 + CZ- ' 0 ' ; 
        CZ=getchar();
    }
    x*=f;
}

 

  Here is the output of the optimization, is not very common, the number of recursive this output (the number of words to the output without recursion is reversed), each output is the number of n% 10, and n / = 10; directly on the code;

Code:

void print ( int y) 
{ 
    if (y < 0 ) putchar ( ' - ' ), y = - y;
    if (y> 9 ) print (and / 10 ); 
    putchar (and % 10 + ' 0 ' ); 
}

  

  This concludes the article, thank you watch.

Guess you like

Origin www.cnblogs.com/tianbowen/p/11299610.html