⭐ Learn Some New C++ Tips and Tricks
1. Header Files
🔴🟡🟢 Instead of using all these header files
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<stack>
#include<fstream>
#include<string.h>
#include<set>
#include<queue>
#include<map>
🔴🟡🟢 Use this
#include<bits/stdc++.h>
2. Data Types
🔴🟡🟢 Use auto to omit data types of the variable in C++
auto a = 'Hello World !';
auto b = 'p';
auto c = true;
auto d = 50;
auto e = 2.5;
▶ C++ will automatically know the data type of the given variable
3. For Loop
🔴🟡🟢 Use range based for loop when needed
▶ Instead of this
int num[] = {2,6,4,7,8};
for(int i = 0 ; i<5 ; i++){
cout << num[i] << endl;
}
🔴🟡🟢 Use this
int num[] = {2,6,4,7,8};
for(auto n: num){
cout << n << endl;
}
4. if else statement
🔴🟡🟢 One liner if else statement
int n = 4;
if(n%2==0){
cout << "Even" << endl;
}
else{
cout << "Odd" << endl;
}
// Use This
int n = 4;
(n%2==0) ? cout << "Even" : cout << "Odd" << endl;
🔴🟡🟢 Check the given number is odd or even using shortcut trick
if(num & 1){
cout << "Odd" << endl;
}
else{
cout << "Even" << endl;
}
5. Swapping
🔴🟡🟢 Swapping of two numbers without using third variable
a ^=b;
b ^=a;
a ^=b;
6. Count numbers of digit
🔴🟡🟢 Count the number of digits using log
int digitCounter (long long n){
return floor(log10(n) + 1);
}