Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot.
- Using the auto keyword to declare datatypes can save a lot of time during programming contests.
When a variable is defined as auto, compiler can determing the datatype on its own.
auto a = 100; // a will become 'int' auto b = 1LL; // b will become 'long long' auto c = 1.0; // c will become 'double' auto d = "variable"; // d will become 'string'
- The watch macro is one of the most useful tricks ever.
#define watch(x) cout << (#x) << " is " << (x) << endl
If you’re debugging your code, watch(variable); will print the name of the variable and its value. (It’s possible because it’s build in preprocessing time.)
- Using typedef’s can save a lot of time of yours which you might spend re-writing the same snippet again and again.
typedef long long ll; typedef pair w; typedef vector va; typedef vector vb; typedef vector vc;
- There’s an inbuilt function to evaluate the greatest common divisor of two numbers. It’s called __gcd() and it’s present in the algorithm header file. To read more about it, refer: https://www.geeksforgeeks.org/stdgcd-c-inbuilt-function-finding-gcd/
- Using “\n” for adding new line breaks is much faster than using “endl”.
- If you use ios::sync_with_stdio(false) at the beginning of your code, you’ll make cin and cout as fast as printf and scanf, but you’ll no longer be able to use neither printf nor scanf.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live