Tips and Tricks for C++ Programmers

Let us add some power and speed potions to your coding skills.
CP (Competitive Programming) is not just about problem solving skills, but also about how fast you solve them.
Here are some cool tricks for your upcoming coding battles if you are a C++ programmer.


\"With great language, comes great library\" :P

The Standard C++ Library comes with some cool header files which provide many useful inbuilt functions. Let us look at some of them.

1) sort(array,array+size)
Yes, that's it. Just one line, your passed array is sorted :P
The time complexity of this sorting function is O(nlogn), which means that it can sort arrays upto a size of 10^6 elements!

Example :
int arr[7]={3,2,5,2,6,1,4};
sort(arr,arr+7); // sorts the array

This function is present in the algorithm header file. Make sure you #include this header file before using this function.

2) reverse(array,array+size)
Function : Reverses any array passed to it.

Example :
char ch[5]={'l','i','v','e','d'};
reverse(ch,ch+5); // changes \"lived\" to \"devil\" :P

Header file : algorithm

3) max(a,b)
Function : Compares the two passed integers a and b, and returns the maximum one.
Header file : algorithm

4) min(a,b)
Function : Compares the two passed integers a and b and returns the minimum one.
Header file : algorithm

5) __gcd(a,b) (Note that it begins with two underscores)
Function : Returns the Greatest Common Divisor of the two passed integers a and b.
Header file : algorithm

Link to some useful string functions ? Click Here :)
Link to some useful math functions ? Click Here :)
Link to some more useful functions ? Click Here :)
Okay Okay enough :P

Tip :
Tired of including too many header files? :P
Just include one single header file in your entire code which includes all the standard, iostream, string, math, algorithm, vector and many more headers:
bits/stdc++.h
You will never need to include another header file for CP again.

Some problems also require some specific Data Structures like Stack, Queue, Vector (Dynammic array), Set, Map, etc. to be solved.
Implementing these data structures can be time consuming, here are some ready-made data structures available in the C++ library :
Click Here


Macros

Saving a default code with pre-defined macros helps you speed up your coding during the contest. (Or if you are too lazy to write too much :P)
Here is a good example :

#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
int a[10],i,s=0;
REP(i,0,9) cin>>a[i]; //takes 10 integer inputs
REP(i,0,9) s+=a[i]; // stores their sum in s
return 0;
}

NOTE: Declaring the main function as \"void\" or including the conio header file in CP results in Compilation Error.



  11    0  
Created On: September 17, 2018 12:20 AM


Comments
There are no comments!

Create an account or login to write a comment

Supported by our Coding Partner