samedi 20 octobre 2018

Using getchar_unlocked()

I recently learnt that using getchar_unlocked() is a faster way of reading input. I searched on the internet and found the code snippet below: But I am unable to understand it.

void fast_scanf(int &number)
{
    register int ch = getchar_unlocked();
    number= 0;

    while (ch > 47 && ch < 58) {
        number = number * 10 + ch - 48;
        ch     = getchar_unlocked();
    }
}

int main(void)
{
    int test_cases;fast_scanf(test_cases);

    while (test_cases--) 
   {
        int n;
        fast_scanf(n);
        int array[n];
        for (int i = 0; i < n; i++)
            fast_scanf(array[i]);
    }
return 0;
}

So, this code takes input for an integer array of size n for a given number of test_cases . I didn't understand anything in the function fast_scanf, like why this line:

while (ch > 47 && ch < 58) 
{ number = number * 10 + ch - 48;

why the register is used while declaring ch?

why the getchar_unlocked() is used twice in the function? and so on.. It would be great help if someone elaborates this for me. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire