Skip to content

[C++] The meaning of ios_base::sync_with_stdio(false) and cin.tie(NULL) in programming competition

Last Updated on 2024-08-25 by Clay

Explanation

On platforms like LeetCode, if one looks at the solutions provided by top coders after solving problems, one often encounters a peculiar piece of code (C++ only):

ios_base::sync_with_stdio(false);
cin.tie(NULL);


This code appears unrelated to solving the problem, so why is it included? The answer is simple: for speed.

In C++, the standard library provides two sets of input/output (I/O) systems:

  1. The C-style stdio (e.g., printf and scanf)
  2. The C++-style iostream (e.g., cin and cout).

These two I/O systems are synchronized by default, meaning they can be mixed in the same code without causing output order issues.

However, while this synchronization ensures that they can work simultaneously, it impacts the performance of the code, especially when performing extensive I/O operations, as the system must execute additional steps to maintain synchronization.

Therefore, in scenarios like programming competitions or programs with heavy I/O tasks, developers often disable the synchronization between iostream and stdio by calling ios_base::sync_with_stdio(false), thus reducing the overhead of I/O operations.

This often leads to significant performance improvements.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version