×

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most should be correct if the operating system is sufficiently developed)," you have probably read in many of the problem statements. Faster I / O systems are key to solving such problems.

For faster and more intuitive input, scanf / printf is often recommended over cin / cout. However, by setting the following two lines in your main (), you can still use cin / cout and get the same functionality as scanf / printf:

ios_base :: sync_with_stdio ( false ) ;

When called before the system performs its first input or output action, it turns on or off the synchronization of all normal C ++ streams and your normal C-stream. This sync can be avoided by adding ios base :: sync with stdio ( false ); (which is automatically true) before every I / O action. Stable member std :: ios base function.

cin.tie ( NULL ) ;

tie () is a function that merely ensures that std :: cout is flushed before std :: cin accepts a command. This is handy for interactive console applications that require the console to be updated on a regular basis, but it slows down the program when dealing with big amounts of data. The NULL portion just returns a reference to NULL.

Furthermore, the standard template library (STL) may be included with a single include:

#include < bits/stdc++.h >

As an example, your competitive programming template may look like this:

#include < bits/stdc++.h >
using namespace std ; 
int main ( )
{
    ios_base :: sync_with_stdio ( false ) ;
    cin.tie ( NULL ) ;
    return 0 ;
}

It is preferable to use cout "n"; rather than cout endl;. endl is more time consuming since it requires a flushing stream, which is frequently unneeded. (If you are upgrading, for example, a collaborative progress bar, you will need to delete it, but not if you are writing a million data lines.) Instead of 'house, write' n. Problem INTEST - Enormous Input Teston SPOJ, we may test our inputs and output methods. I recommend that you tackle the problem first before continuing.

Example:

// A normal IO example code
#include < bits/stdc++.h >
using namespace std ;
int main ( )
{
	int n , k , t ;
	int cnt = 0 ;
	cin >> n >> k ;
	for ( int i=0 ; i < n ; i++ )
	{
		cin >> t ;
		if ( t % k == 0 )
			cnt++ ;
	}
	cout << cnt << "\n" ;
	return 0 ;
}

OUTPUT:

0
...
Process executed in 2.11 seconds
Press any key to continue.

Explanation

cin and cout are used in the code below. With a runtime of 2.11 seconds, the solution is acceptable.

Another Example:

// A fast IO program
#include < bits/stdc++.h >
using namespace std ; 
int main ( )
{
	// added the two lines below
	ios_base :: sync_with_stdio ( false ) ;
	cin.tie ( NULL ) ; 
	int n , k , t ;
	int cnt = 0 ;
	cin >> n >> k ;
	for ( int i = 0 ; i < n ; i++ )
	{
		cin >> t ;
		if ( t % k == 0 )
			cnt++ ;
	}
	cout << cnt << "\n" ;
	return 0 ;
}

OUTPUT:

0
...
Process executed in 0.22 seconds
Press any key to continue.

Explanation

By adding two lines, we can improve the performance and significantly cut the runtime. With a runtime of 0.22 seconds.

Another Example:

#include < bits/stdc++.h >
using namespace std;
void fastscan ( int &number )
{
	//variable to indicate sign of input number
	bool negative = false ;
	register int c ; 
	number = 0 ; 
	// extract current character from buffer
	c = getchar ( ) ;
	if ( c == '-' )
	{
		// number is negative
		negative = true ; 
		// extract the next character from the buffer
		c = getchar ( ) ;
	}
	// Keep on extracting characters if they are integers
	// i.e ASCII Value lies from '0'( 48 ) to '9' ( 57 )
	for ( ; ( c > 47 && c < 58 ) ; c=getchar ( ) )
		number = number *10 + c - 48 ; 
	// if scanned input has a negative sign, negate the
	// value of the input number
	if ( negative )
		number *= -1 ;
}
// Function Call
int main ( )
{
	int number ;
	fastscan ( number ) ;
	cout << number << "\n" ;
	return 0 ;
}

OUTPUT:

0
...
Process executed in 0.12 seconds
Press any key to continue.

Explanation:

Now, when it comes to competitive challenges such as the ACM ICPC, Google CodeJam, and TopCoder Open, above is a unique code for reading numbers quickly.


Related Topics

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.