This shot will discuss certain
\n
instead of endl
When you submit the coding solution on an online coding platform, we get to see the
One solution is to avoid the use of endl
to print the next line character in your solution. This is because the endl
operator prints the new line character, but it also flushes the output stream, which leads to a higher execution time. For a lower execution time, use \n
.
bits/stdc++.h
When working with bits/stdc++.h
, the header file for all the libraries in C++.
typedef
Generally, in competitive coding contests, you do not have time to declare long data type declarations like vector<int, int>
or vector<pair<int, int>, bool>
.
Instead, use typedef
to declare these type names at the start of your program. Then, they can easily be used whenever you require them in the rest of the code.
Let’s look at the code below to better understand this.
#include <bits/stdc++.h>using namespace std;typedef long long ll;typedef vector<int> vi;typedef vector<pair<int, bool>> vpib;int main() {ll a = 123456789;cout << a << "\n";vi vec = {1,2,3,4,5};vpib vpair = {{1,true}, {2, false}};return 0;}
In line 1, we used bits/stdc++.h
to import all the header files instead of importing each of them one by one.
From lines 4 to 6, we used typedef
to declare the type names.
In the main()
function, we used the
Macros replace certain statements in the code before the compilation. They help reduce the effort of writing the same thing again and again in the code.
For example, imagine you have a vector and you use the push_back()
method to insert an element into the vector. Here, you can create a PB
macro that will be replaced every time as push_back
. Macros can also have parameters.
Let’s look at the code below to understand this better.
#include <bits/stdc++.h>using namespace std;#define PB push_back#define MP make_pair#define FIN(a , b) for(int i = a; i < b; i++)int main() {vector<int> vec;vec.PB(10);vec.PB(20);FIN(0, vec.size())cout << vec[i] << " ";return 0;}
PB
macro instead of using push_back
.Macros can thus be useful to reduce repeated code and write the code faster.
cin
in a loopIn many problems, we are given a stream of inputs where we do not know how many inputs there are. We can use cin
in a loop, where the loop accepts the input until your input becomes NULL
. Let’s look at the code below to understand this better.
Enter a number below.
#include <iostream>using namespace std;int main() {// your code goes hereint n;while(cin >> n){cout << n << " ";}}
Enter the input below
while
loop to run until there are no more inputs present.This will allow you to enter any number of inputs.
These tips will hopefully help you to write code in better and faster ways.
Check out my course Competitive Programming - Crack Your Coding Interview, C++ to help you prepare for your upcoming coding interviews.