Some Useful Tricks in C++

Some Useful Tricks in C++

2 min read

1.) Do use using statement :- Common data-stream objects cin and cout are members of std namespace, requiring to write code like this:

std::cout<<“Hello”<<std::endl;

Strongly recommendations is bringing in the entire std namespace , thus eliminating the need to use std:: prefix with cin, cout etc.

using namespace std;

2.) Swap numbers using XOR :- This is more efficient and doesn’t required a third variable.

x=x^y;
y=y^x;
x=x^y;

3.) Use return value of “cin>>” to check end of file.

while(cin>>x) //statement

4.) Binary Shifting :- Do fast multiplication or division with 2 using binary shifting.

x=x<<1;      // Multiplication with 2
x=x>>1;     // Divide by 2

5.) Getting rid of includes :- Normally to use different containers (such as sets,maps) , we have to include a lot of different includesin our code which makes it bulky. Rather we can simply include bits/stdc++.h in the code .Ex:-

  #include<iostream.>
#include<list>
#include<deque>
#include<set>
#include<iomanip>
#include<string>
#include<cmath>
#include<mao>
#include<vector>

// instead we can use just

#include<bits/stdc++.h>

6.) Using typedef can save a lot of time instead of spending time in rewriting the same snippet again and again . Ex:-

typedef vector va;
typedef pair w;
 typedef vector vb;

7.)(i) Don’t use global variables except to communicate between functions.

(ii) Do us elocal variables with the for loop statement .

8.) (i) Do remember: Semicolon’s after class(including struct and unions ) declarations , not functions.

(ii) Don’t be intimidated into overusing classes and objects .

9.) Using emplace_back in place of push_back :- emplace_back just works like push_back adding elements at the end of a vector . emplace_back is faster than push_back as push_back first creates a temporary variable and then adds it to the end of vector.

vector<int> v;
v.push_back(1);      // Slower
v.emplace_back(2);      //Faster

10.) Finding gcd:- Instead of writing the eucledian algorithm for finding gcd of two numbers you can simply use the predefined gcd function.

Ex:- int a= gcd(12,10);

THANK YOU

Choose your Reaction!
Leave a Comment